Objective-c has supported the use of Generics since Xcode 7. Generics do not specify the type, but determine the type at the time of use.

Syntax: type < restricted type >. Such as: NSArray < nsstrings * >

Usage scenarios

1. The use of generics in collections (arrays, dictionaries, NSsets) is common. 2. We use generics when declaring a class whose properties are of indeterminate type.

The role of generics

  • Limits the type of elements in a collection. Improve code specification and reduce communication costs.

For example, create an array that can only hold nsStrings

NSMutableArray< NSString *> *array = [NSMutableArray array];
Copy the code

For example, declare an array property that can hold only UIViewController

@property (nonatomic, copy) NSArray<UIViewController *> *viewControllers;
Copy the code

So the array here, the elements are definitely of type UIViewController, and you get a warning if you add an element that’s not of type UIViewController. In addition, its subclasses also have warnings, in which case the __kindof keyword is needed.

@property(nonatomic,copy) NSArray<__kindof UIViewController *> *viewControllers;
Copy the code

__kindof: Extends generics to support subclasses.

So once you do that, there’s no warning even if you add a UIViewController subclass to the array.

  • Facilitate access to the object properties of the collection
@property (nonatomic,strong) NSArray <PDCar *> *dataSource;
Copy the code

There are no generics. You can access properties of objects inside an array only through getters. You can’t use dot syntax because the value returned by index is of type ID.

With generics, the type of the return value is determined. You can click the syntax to directly access the attributes of an element.

float p = self. dataSource[0].price;
Copy the code

Generic + protocol

If you declare a generic and expect the object to respond to a specific method/property, you can attach a protocol to the generic.

@protocol SomeProtocol <NSObject> @property (nonatomic, copy) NSString *name; @end ... @interface ViewController () @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSArray <UIViewController <SomeProtocol> *> *array; / / call the - (void) useGenericProtocol {nsstrings * name = self. Array. FirstObject. Name; NSLog(@"name-> %@", name); } @endCopy the code