iOS Learning Notes (01)-Generics

Source: Internet
Author: User

decided to open a new hole in the continuous learning while sharing their learning process to everyone, not only the record of their own learning, but also hope to provide you with a bit of help.

  

This article mainly introduces the meaning of generics, how to use and declare, and so on.

1. Generics: restriction type

1.1. Generic usage Scenarios :

1. It is common to use generics in collections ( array nsarray, dictionary nsdictionary, Collection nsset) .

    2. generics are used when declaring a class, but the types of certain properties inside the class are not deterministic .

1.2 . Generic Writing specification

    Define generics after type:nsmutablearray<uitouch *> DataArray

1.3 . generic adornments

    Only the invocation of the method can be decorated.

1.4. Generic Benefits :

1. improve the development of the specification, reduce the communication between programmers.

2. objects taken from the collection can be used directly as generic objects. So we can use it directly . Dot syntax.

  

2. The code uses generics:

2.1. Declaring an array with a generic type of nsstring

1//The practice is to take a <nsstring *> after Nsmutablearray, which is a generic type inside the angle brackets
2 @property (nonatomic, Strong, nullable) nsmutablearray<nsstring *> *dataarray;

2.2. When we want to add an object to an array or take out an object, the system automatically prompts for the type of the object that should be passed in or out, which is the generic type you just declared.

1     //1. No generics are used2 //[Self.dataarray addobject:<# (nonnull ID) #>];3 4     //2. Using generics5 //[Self.dataarray addobject:<# (nonnull nsstring *) #>];6     7     //3. Add an incorrect type and a warning will appear8 //[Self.dataarray addobject:@1];9     Ten     //4. We can directly use the objects that are taken out of the collection as generics OneNsinteger length = [self.dataArray.firstObject length];

  

Basically, it is possible to use a generic procedure.

3. Generics customization

Just now we just implemented the generic type of the system class Nsmutablearray. Next we'll consider how do we declare a generic property in our own class?

For this purpose, we create a Language class that represents "language". and create a subclass of two Language, called Java and IOS, respectively. It is obvious that these two are "one type of language". We create a class of person, declare a generic to the class, declare a property in the. h file of the class, and this property represents the language of the human being, that is, IOS or Java. Then we have the following two ways of declaring:

 1  //  2  //  1.id: Any object can be passed in  3  @ Property (Nonatomic, Strong, null_unspecified) ID language;  4   2. Language: When calling outside, it is not possible to prompt the specific language  5  //   @property (nonatomic, Strong, null_unspecified) Language *language;  

Because Language this language does not represent what language this person actually will be, we need the properties of IOS and Java. Both of these can be passed on to Java and IOS two objects at the time of invocation, but their drawbacks are obvious, and if you use IDs we can pass in any object, not just Java and iOS, and with Language * We have no way of determining what language the person will be at compile time, but only Can be judged at run time. Is there any way to let us know what kind of Language the person will be when compiling?

The solution is generic.

Declaring a generic for a custom class, we need to do one of these steps:

1 // declare a generic (to a Class) 2 @interface Jtperson<objecttype>: NSObject

Do you see the difference? We added a pair of angle brackets <> after the interface class name, ObjectType in the middle. This represents generics. So we can write this when we declare the attributes:

1 @property (nonatomic, Strong, null_unspecified) ObjectType language;

That is, we do not specify a specific type now, but when instantiating this class, we determine this generic type. If you are unsure, all ObjectType will automatically become the ID. Like this:

1     //IOS2Jtperson<ios *> *iosp =[[Jtperson alloc] init];3      4 //[Iosp setlanguage:@ "123"];5     6 //[Iosp setlanguage:<# (IOS * _null_unspecified) #>];7     8 //[Iosp Setlanguage:[[java alloc] init]];9     Ten     //Java OneJtperson<java *> *JAVAP =[[Jtperson alloc] init]; A      - //[JAVAP setlanguage:@ "123"]; -      the //[Javap setlanguage:<# (Java * _null_unspecified) #>]; -      - //[Javap Setlanguage:[[ios alloc] init]];

This way, when we declare the class of person, we declare the generic type of this class. The system will automatically alert you to the generic type you declared when you use the generic properties and methods.

4. Covariance and contravariance of generics

First, let's look at a method:

1 -(void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (uievent *)event  {  2     3    [touches anyobject]; 4 }

You should be familiar with this method. This is how Uiviewcontroller inherits from Uiresponder, which is the last link in the event chain after clicking on the view controller. As we go through the above study, we will see that it uses generics: (nsset<uitouch *> *). So we'll go into the collection and Nsset will find it written like this:

Before and after we all know: interface: declaration; Nsset: set; ObjectType: generic; NSObject: is the parent of Nsset and the root class;

So what does __covariant represent?

Here we first learn two words: covariant: contravariant of covariant : Inverse variable.

So what does __covariant mean?

 

Let's try it out. Add such a modifier to the generic ObjectType of the custom class person just before: __covariant

1 @interface Jtperson<__covariant objecttype>: NSObject

And then, at the time of invocation, we declare two instances, the generic type is the parent class Language and the subclass IOS. So what happens if a person who is a generic IOS wants to assign a value to a person with a generic type of Language:

1     // 1. Co-change 2     // IOS 3     Jtperson<ios *> *iosp = [[Jtperson alloc] init]; 4     5     // Language 6     Jtperson<language *> *p = [[Jtperson alloc] init]; 7     8     // if the subclass wants to assign a value to the parent class, the covariant 9     p = iosp;

and no error.

That is, if an object of the generic subclass wants to assign a value to an object of the generic type, we need to add the covariant __convariant to the compiler before the generic, so there is no problem with the conversion.

Similarly, the __contravariant inversion is that if the generic is the parent of an object that wants to assign a value to an object of the generic subtype, we need to add the inverse __contravariant to the compiler before the generic, so that the conversion is no problem.

This is the meaning of covariance and contravariance.

Covariance and contravariance are inherently a feature of object-oriented languages and are not only applied to generics here.

iOS Learning Notes (01)-Generics

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.