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

Very often, I find that I throw objects in NSArray into my types when I want to access their specific properties using dot notation (instead of getter) without creating an additional variable.

Is there any interesting function or trick to tell objective-c which one class of objects I'm going to store in NSArray, so that the compiler assumes that the objects in the array will be my types and not id?

+4
source share
3 answers

If you mean that you do things like:

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

You can simply split it into two lines to make them easier to read:

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

If you are really tuned in the first case, you can create 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 the way you want:

 x = [myArray myClassObjectAtIndex:2].property1; 
+6
source

Do not use properties in this situation. You can't say

 arr[ix].myProperty 

But you can always say

 [arr[ix] myProperty] 
+2
source

Strictly answering your question, no.

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

However, you can find workarounds to avoid explicit casts.

Since the returned object is of type id , you can call any existing method on it, and the compiler will not raise an eyebrow if you do not use point-syntactic notation, which has more stringent compiler checks.

So for example

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

works flawlessly without casting, whereas

 NSString * name = people[0].firstName; 

not.

+1
source

Source: https://habr.com/ru/post/1499978/


All Articles