New charm of objective-c language--nullability, generic set and type extension

Source: Internet
Author: User

The new charm of objective-c languageFirst, Introduction

in Xcode7, the IOS9 SDK has been fully compatible with some of the new features and features of Objective-c. These features are only used for the compilation period, no impact on the operation of the program, so it can be very good down compatible, seamless convergence of the low version of the iOS system, then what is the use of these features, as a developer, I guarantee you will love them, if you can apply these new features to your development, Your development efficiency and code quality, compared to before, there will be a great upgrade.

Second, the support of nullability detection

in the swift language, through! and? You can declare an object as optional, which is used to mark whether the object can be empty in development. In OC, there was no such function in the past, so we would often encounter crashes caused by a function returning an empty instance in development. The main thing about nullability is that it can be a hint to the developer whether or not to be judged as empty.

Open Xcode7, nullability is already supported in the framework of the system, as follows:

@property (Nullable, Nonatomic, ReadOnly) ObjectType Firstobject; @property (Nullable, Nonatomic, ReadOnly) ObjectType Lastobject;

This is the two attribute in Nsarray, where the Nullable keyword indicates that an empty value may be returned here.

If you just give the developer some hints in the return value, you may feel that the application is not very big, yes, the greatest help to developers is that this feature can be used in the parameters of the function, so that we call the function when the hint, it will be very important, the more people cooperate the project, the greater the role.

For example:

-(void) SetValue: (NSNumber * _nonnull) number{}

When we call the function, if we pass in a null value, the compiler will give us a warning:

Attention:

This feature has been supported in Xcode6.3, but there have been some minor changes in Xcode7, such as writing in Xcode6.3:

-(void) SetValue: (nonnull nsnumber *) number{}

In Xcode7, we are encouraged to use the first notation.

Some of the key words are as follows:

Modifier parameters

Nonnull: cannot be empty

Nullable: Can be empty

Null_unspecified: Not sure if it can be empty (very few cases)

In the declaration of a property, there is also the following modifier:

Null_resettable:set method can not return nil for Nil,get method

A little hint:

You can see that the IOS9 SDK is fully compatible with these features, and nonnull is much more widely used than nullable, so the system provides a pair of macros:

#define Ns_assume_nonnull_begin _pragma ("clang assume_nonnull BEGIN")

#define Ns_assume_nonnull_end _pragma ("clang assume_nonnull END")

The variables we define between the macros are prefixed with the nonnull modifier, and only those of us who specifically declare nullable need to be written manually.

iii. support for generic collections

This feature, like nullability, is used only for compile time and is another important feature that serves our developers. Remember, before Xcode7, is still to facilitate the development of many people, I often write in the framework such an empty macro:

The following is used at development time to prompt the partner what is the function of this array of things:

@interface Viewcontroller () {Nsarray __type__fit_to__class (nsstring) * array;} @end

Of course, all of these are my own self-directed self-acting, the compiler does not bird me, I add other things in this array, it does not mind, all these are just a kind of wishful thinking that I and my partners have agreed. So, when I saw the collection type in Xcode7, I was really excited.

1. A set of type conventions

In Xcode7, we can add a generic convention to the collection type as follows:

nsmutablearray<nsstring *> *array = [[Nsmutablearray alloc]init];

After declaring such an array, it is like I told the compiler that the data types in this array are nsstring* types, and now very well, if I am the method of the elements in this array, the following hint will appear:

Get excited, using dot syntax, you can access the methods of generics in the array, and more tempting:

As we append elements to this array, the compiler hints at the type of the element and prompts for the type of element required in the FromArray method.

Similarly, if we append an element of type mismatch to this array, the following:

nsmutablearray<nsstring *> *array = [[Nsmutablearray alloc]init]; [Array addobject:@1];

The compiler will give us a warning like this:

2. About a type wildcard character

Observing the class of iOS system in Xcode7, we can find such a fun thing: ObjectType. It is neither a type nor a keyword, but a large number exists, as follows the system's Nsmutablearray header file:

@interface nsmutablearray<objecttype>: nsarray<objecttype>-(void) AddObject: (ObjectType) anobject;-( void) InsertObject: (ObjectType) AnObject Atindex: (nsuinteger) index;-(void) removelastobject;-(void) Removeobjectatindex: (Nsuinteger) index;-(void) Replaceobjectatindex: (nsuinteger) Index Withobject: (ObjectType) anobject;-(instancetype) init ns_designated_initializer;-(instancetype) initwithcapacity: (NSUInteger) NumItems NS_ designated_initializer;-(Nullable Instancetype) Initwithcoder: (Nscoder *) Adecoder Ns_designated_initializer; @end

This objecttype is actually just a type identifier, it does not matter how to write, but the system is agreed to use the ObjectType, you can also in their own class in accordance with their own preferences to name, this thing has what kind of use, I use the text description is not clear, We can define a collection class by ourselves to understand:

Create a class that inherits from NSObject, and I take the name myarray:

The wildcard character of this type can only be used in Interfave, the scope is between @interface to @end//Here I use the type to do this wildcard @interface myarray<type>: Nsobject@property (nonatomic,strong,nonnull) nsmutablearray<type> *array;-(void) AddObject: (nonnull Type) obj; @end

The implementation is as follows:

-(instancetype) init{self = [super init];    if (self) {_array = [[Nsmutablearray alloc]init]; } return self;} -(void) AddObject: (ID) obj{[_array addobject:obj];}    -(NSString *) description{nsmutablestring * str = [[nsmutablestring alloc]init];    for (int i=0; i<_array.count; i++) {[str appendstring:[nsstring stringwithformat:@ '%@\n ', _array[i]]; } return str;}

When we use this custom collection type, we have the same effect as the system:

3, about the multi-parameter generic collection

Multi-parameter generic collection, there is a very good example, is nsdictionary, in Xcode7 we can write the dictionary:

As you can see, the type compiler for the dictionary key value is prompted for us, combined with the use of the above type wildcard character, for the set of multi-parameter, the parameter type is separated by ",".

4. Covariance and inverse degeneration

Because of the concept of generic collections, our types are actually more complex than before, such as taking our own custom collection types for example:

myarray<nsstring *> * array; Myarray<nsmutablestring *>*muarray;

Arrays and Muarray appear to be different types in the compiler, and if we force conversions, we will report the following warning:

Thus, there is the concept of contravariance and covariance:

__covariant: A subtype pointer can be converted to a parent type pointer

__contravariant: The parent type pointer can be converted to a sub-type

In the above case, we will change the custom class as follows, without warning:

@interface myarray<__covariant type>: Nsobject@property (nonatomic,strong,nonnull) nsmutablearray<type> *array;-(void) AddObject: (nonnull Type) obj; @end
Application of type extension character

In development, developers often encounter such situations, such as the use of tags to get some UI controls, the Viewwithtag method will usually return to us a uiview type of pointer, which requires the developer manual strong turn, very troublesome. The newly added __kindof modifier helps us to relieve this annoyance. We also cut from the custom array class and add a property to it:

@interface myarray<__covariant type>: Nsobject@property (nonatomic,strong,nonnull) nsmutablearray<type> *array; @property (nonnull,strong,nonatomic) nsmutablearray<uiview *> * viewarray;-(void) AddObject: (nonnull Type) obj; @end

Create a custom Array object and add a UIButton to it, and we'll see a warning like this:

This is the problem we often encounter in the development, right, before the need for strong turn. But we don't need it in the future, we'll add a __kindof modifier when declaring this array:

@property (nonnull,strong,nonatomic) nsmutablearray<__kindof UIView *> * viewarray;

The warning disappears, it's cool.

This modifier is to tell the compiler that you can return the UIView pointer to the child class.

V. Conclusion

Although these advantages are reflected in swift, but personally, my feelings for OC will be deeper, but also more willing to accept the change and growth of OC, we all say that the swift trend is imperative, I just want to say that Swift is excellent, and OC.

New charm of objective-c language--nullability, generic set and type extension

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.