3

Is there a way to cast objects in objective-c?

For example, I have that object and want to cast it into a class:

NSManagedObject *item = [array objectAtIndex:indexPath.row];  
Popeye
  • 11,839
  • 9
  • 58
  • 91
mowi
  • 79
  • 1
  • 2
  • 6

2 Answers2

17

I guess you want like this:

if ([[[array objectAtIndex:indexPath.row] isKindOfClass:[NSManagedObject class]])
{
    NSManagedObject *item = (NSManagedObject *)[array objectAtIndex:indexPath.row]; 
}

Have a look at this link first, under Auto Generating Model Files, see how author changed NSManagedObject to a strongly typed object.

So what will be left for you is:

if ([[[array objectAtIndex:indexPath.row] isKindOfClass:[Contact class]])
{
    Contact *item = (Contact *)[array objectAtIndex:indexPath.row]; 
}

Hope that helps!

NeverHopeless
  • 11,077
  • 4
  • 35
  • 56
2

Yes simply do

NSManagedObject *item = (NSManagedObject *)[array objectAtIndex:indexPath.row];  
Popeye
  • 11,839
  • 9
  • 58
  • 91