generics: restriction type
Usage scenarios in development: 1. Restrict the types in the collection, only the invocation of the method, because the declared generic can only exist in method 2. When a class is declared, the properties of an object are indeterminate, and generics can be used only when the object is created. Define a generic writing format: Placed behind a type, indicating the restriction of this type// Defining generics:Determine type
@property (nonatomic, strong) nsmutablearray<NSString *> *array;
This defines a type that represents only nsstring in the array
When we call Self.array AddObject, Xcode prompts us to pass in the type NSString type
I fetch directly to the first element in the array
Self . Array [0]. Length can be called directly by the length function of NSString The default one-step type conversion
Declaring generics in a class:
// declaration generics: Indeterminate type
@interface person< objecttype>: nsobject
@property (nonatomic, strong) ObjectType car;
@end
You can pass in the type directly when you create the object:
Person <Car *> *p = [[ person alloc]init]; The type of car variable inside the object p is the car type.
Benefits of Generics:
Improve programmers ' development specifications and reduce communication costs
the values taken from the array and the dictionary are ID types, the point syntax cannot be called, and the generics can call point syntax
Default with generic variables can be assigned a warning, using covariance and contravariance to solve a warning problem
__covariant covariant upward transformation, subclass to parent class
__contravariant inversion downward transformation, parent class rotor class
The parent class of Sedancar is car class
// DECLARE generic: __covariant keyword used when declaring
@interface Person<__covariant objecttype>: nsobject
@property (nonatomic, strong) ObjectType language;
@end
Then Person <Car *> *p1 = [[ person alloc]init];
Person <sedancar *> *p2 = [[ person alloc]init];
P1 = p2;
P2 assignment to P1, there's no warning.
If you use the __contravariant keyword to assign P1 to P2, no warning is generated
__kindof: Equivalent , representing a class or his subclass
The design model can be used when providing a class method to a class that wants outside calls to see what objects are created and does not report a warning.
@interface Person: NSObject
@property (nonatomic, strong) nsstring *name;
+ (__kindof person *) person;
@end
IOS9 new features, generics