Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: Is there any trick to avoid casting of NSArray objects?

Very often I find myself casting objects in NSArray to my types, when I want to access their specific properties with dot notation (instead of getter) without creating an extra variable.

Is there any cool feature or trick to tell objective-c which one class of objects I'm going to store to NSArray, so that compiler will assume objects in an array to be my type, not an id?

like image 452
ambientlight Avatar asked Jan 12 '23 11:01

ambientlight


1 Answers

If you mean you're doing things like:

x = ((MyClass *)[myArray objectAtIndex:2]).property1;

You can just split it into two lines to be easier to read:

MyClass *myObject = [myArray objectAtIndex:2]
x = myObject.property1;

If you're really set on the first case, you could make a category on NSArray that has an accessor for your type:

@implementation NSArray (MyCategory)

- (MyClass *)myClassObjectAtIndex:(NSUInteger)index
{
   return [self objectAtIndex:index];
}

@end

And then you can use it like you want:

x = [myArray myClassObjectAtIndex:2].property1;
like image 80
Carl Norum Avatar answered May 16 '23 07:05

Carl Norum