In NSArray.h I saw the interface like this
@interface NSArray<ObjectType>
What is the significance of <ObjectType>
?
Using - (BOOL)isKindOfClass:(Class)aClass in this case would result in TRUE both times because the inheritedClass is also a kind of the superClass. isMemberOfClass: will return NO when dealing with subclasses.
For Objective-C, does it has Generics as well? The answer is yes. Apple introduces Generics in Objective-C since 2015. The main goal is to enable Swift Generics to convert to Objective-C syntax without extra overhead (as it is called as “lightweight generics”).
Objective-C Classes Are also Objects In Objective-C, a class is itself an object with an opaque type called Class . Classes can't have properties defined using the declaration syntax shown earlier for instances, but they can receive messages.
NSCFNumber is a concrete, "private" implementation of a class in that cluster.
That is Apple using lightweight generics. The full @interface
declaration in Xcode 7.3.1 looks like this:
@interface NSArray<__covariant ObjectType> : NSObject <NSCopying, NSMutableCopying, NSSecureCoding, NSFastEnumeration>
ObjectType
is a placeholder used to represent the generic argument you pass into so that the compiler knows where to reference them. This is different than using NSObject *
because ObjectType
is like id
, it can refer to non-Objective-C pointer types such as CoreFoundation objects.
For example, if I wanted to create a class that mocks an array for only a specific class, I could do something like @interface MYArray<MyClass *>
.
You could also specifically declare an array of strings as NSArray<NSString *>
.
See this article on Objective-C Generics for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With