Objective-c three Xin Features

Source: Internet
Author: User

Http://www.cocoachina.com/ios/20150617/12148.html

Overview

Since the launch of the WWDC 2015 and the Open source Swift 2.0, everyone's enthusiasm for Swift has soared again, while the envious startups ' friends talk about Swift's new features, as well as many developers who still need to stick to the objective-c language as I do at work. This year's WWDC introduced a few new features of the Objective-c language, or in the "Working with Swift" Topic, which underscores the marginalization of the language, but the new features are excellent, and next, this article will cover the following three main new features:

    • nullability

    • Lightweight generics *

    • __kindof

nullability

However, nullability is not a new feature and has been supported from the previous version of LLVM 6.1 (Xcode 6.3). This simple version of the Optional, no Swift? And! The support of grammatical sugars is very verbose in objective-c:

123 @property (nonatomic, strong, nonnull) Sark *sark;@property (nonatomic, copy, readonly, nullable) NSArray *friends;+ (nullable NSString *)friendWithName:(nonnull NSString *)name;

If it is used to modify a variable, the front has to double underline, put into the block inside is more strange, such as a Request of the Start method can be written as:

1 - (void)startWithCompletionBlock:(nullable void (^)(NSError * __nullable error))block;

In addition to these two, there is a null_resettable to show setter nullable, but Getter Nonnull, the most intuitive example is the View property in Uiviewcontroller:

1 @property (null_resettable, nonatomic, strong) UIView *view;

It can be set to nil, but invoking a getter triggers-loadview to create and return a non-nil view.

From the iOS9 SDK, it can be found that all the APIs in the header file have been added to the nullability related modifiers, to understand the use of this feature, flipping through several system header files is're far off. Interface Nullable is a few, so in order to prevent writing a large number of nonnull,foundation also provides a pair of macro, the object is wrapped in the default add nonnull modifier, only need to put nullable point to the line, slang called audited Regions:

1234567 NS_ASSUME_NONNULL_BEGIN@interface Sark : NSObject@property (nonatomic, copy, nullable) NSString *workingCompany;@property (nonatomic, copy) NSArray *friends;- (nullable NSString *)gayFriend;@endNS_ASSUME_NONNULL_END

Nullability provides a type check of NULL values at the compiler level, giving warning when the type does not match, allowing developers to discover potential problems the first time. But I think the bigger point is to be able to describe the interface more clearly, is a protocol between the main and the tune, and it's clearer than how many documents are described, for example:

1 + (nullable instancetype)URLWithString:(NSString *)URLString;

Nsurl this API before the addition of nullable, more explicitly pointed out that this interface may be due to the URLString format error and create a failure, the use of the natural consideration of the empty processing.

Not only the properties and objects in the method, for local objects, and even C pointers can be used with double underscore modifier, can be understood to be able to use the Const keyword where can be used nullability.

So nullability is, in general, writing ugly B, with a comfortable

Lightweight generics

Lightweight generics lightweight generics, lightweight because this is a pure compiler syntax support (LLVM 7.0), like nullability, without any OBJC runtime upgrades, that is, this new syntax can be used on Xcode 7 and fully backwards compatible (lower IOS version)

A container with a generic type

This is undoubtedly the most significant improvement, and with generics you can finally specify the type of objects in the container class:

12 NSArray *strings = @[@"sun", @"yuan"];NSDictionary *mapping = @{@"a": @1, @"b": @2};

After the ID of the return value is replaced with a specific type, the moving code hints come out:

If you add the wrong object to the generic container, the compiler will be unhappy:

The range of container types commonly used in the system adds generic support, even nsenumerator, which is a very nice improvement. Like nullability, I think the most important thing is to enrich the interface description information, and compare the following two kinds of wording:

12 @property (readonly) NSArray *imageURLs;@property (readonly) NSArray *imageURLs;

Don't think about it and know what's in the array below, avoiding the chaos of NSString and Nsurl.

Custom generic Classes

More fun than using a system generic container is to customize a generic class, and there's no documentation here, but it doesn't stop us from writing the test code, assuming we want to customize a Stack container class:

12345 @interface Stack : NSObject- (void)pushObject:(ObjectType)object;- (ObjectType)popObject;@property (nonatomic, readonly) NSArray *allObjects;@end

This ObjectType is an incoming type of placeholder, it can only be defined on the @interface (class declaration, Class extension, category), if you prefer T to be OK, this type in the scope of @interface and @end range is valid, you can It should be said that everything is expected to be a generic type that is an entry, a parameter, or even an internal nsarray property. We can also add type restrictions to ObjectType, such as:

1234 // 只接受 NSNumber * 的泛型@interface Stack : NSObject// 只接受满足 NSCopying 协议的泛型@interface Stack<objecttype: id> : NSObject</objecttype: id>

If nothing is added, the expression accepts any type (ID), and the compiler generates an error when the type is not satisfied.

Instantiate a Stack, everything works fine:

For multi-parameter generics, separated by commas, the other is the same, you can refer to the Nsdictionary header file.

Covariance and inverse degeneration

When a class supports generics, their type changes, such as the following three objects appear to be Stack, but actually belong to three types:

12 Stack *stack; // Stack *Stack *stringStack; // StackStack *mutableStringStack; // Stack

When two of these types do type conversions, the compiler needs to know which conversions are allowed and which are forbidden, for example, by default:

As we can see, a Stack that does not specify a generic type can be converted with any generic type, but after a generic type is specified, two different types cannot be strongly turned, and if you want to actively control the conversion relationship, you will need to use the generic covariance and inverse modifiers:

__covariant-covariance, subtypes can be strongly transferred to parent type (Richter substitution principle)

__contravariant-Inverse, parent type can strongly go to subtype (WTF?)

Co-change:

1 @interface Stack : NSObject

Effect:

Inversion:

1 @interface Stack : NSObject

Effect:

Covariance is very well understood, and generics like Nsarray use covariant modifiers, and contravariance I haven't thought of any actual usage scenarios.

__kindof

__kindof This modifier is still very practical, solve a long-term small pain point, take the original UITableView this method:

1 - (id)dequeueReusableCellWithIdentifier:(NSString *)identifier;

Using a pointer to the UITableViewCell subtype is used to receive the return value, so the API is designed so that the developer does not have to write explicit strong turns each time the egg hurts, the return value is defined as the ID type, and the API actually means to return a UITableViewCell Or an instance of the UITableViewCell subclass, the new __KINDOF keyword solves the problem:

1 - (__kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier;

The return value is clearly indicated and the user does not have to write a strong turn. To give an example with generics, the Subviews property of UIView is changed to:

1 @property (nonatomic, readonly, copy) NSArray *subviews;

This way, there is no warning when writing the following code:

1 UIButton *button = view.subviews.lastObject;

Where to go

With these new features described above and historical updates such as instancetype, the type detection and type inference of Objective-c's ancient language has finally improved, and there are now fewer types of IDs in both interfaces and code. More potential type errors can be found by the static check of the compiler.

At the same time, the personal feel of the new version of Xcode on the inheritance chain constructor detection also strengthened,Ns_designated_initializer This macro is not a new face, you can use it to mark the same as Swift, the constructor and the convenient constructor.

Finally, with a piece of code that uses all the new features, Swift is a trend, and if you are still writing objective-c code for the time being, use all the new features, perhaps making your migration to the new language painless.

References

    • Https://msdn.microsoft.com/zh-cn/library/dd799517.aspx

    • Https://gist.github.com/jtbandes/881f07a955ff2eadd1a0

Objective-c three Xin Features

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.