Search code examples
objective-cgenericsnsarray

<ObjectType> in Objective-C


In NSArray.h I saw the interface like this

@interface NSArray<ObjectType>

What is the significance of <ObjectType>?


Solution

  • 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.