Question

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?

Était-ce utile?

La solution

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;

Autres conseils

Don't use properties in this situation. You can't say

arr[ix].myProperty

But you can always say

[arr[ix] myProperty]

Strictly answering to your question, no.

There's no language support for indicating the parametric type of a collection, i.e. something like NSArray<MyClass>.

That said, you can find workarounds for avoiding an explicit cast.

Since the returned object is of type id you can invoke any - existing - method on it and the compiler won't raise an eyebrow, unless you're using dot-syntax notation, which has stricter compiler checks.

So for instance

NSString * name = [people[0] firstName];

works flawlessly without a cast, whereas

NSString * name = people[0].firstName;

doesn't.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top