InitializerYou should be familiar with this.
- (id)initWithSomething;
Convenience constructorHowever, in practice, we often use the following statements:
[[Foo alloc] init];
If you define this product as a method, as follows:
+ (id)buildInstance;
In addition to simple writing, what is the difference?Initializer is automatically written by the compiler as follows:
- (instancetype)initWithSomething;
Convenience constructor will not be optimized by the compiler. Therefore, problems may occur, such as the following:
Foo. h#import
@interface Foo : NSObject+ (id)buildInstance;- (id)init;@end
Foo. m#import Foo.h@implementation Foo+ (id)buildInstance{ return [[self alloc] init];}- (id)init{ return [super init];}@end
At this time, you call:
[[Foo buildInstance] doSomethingElse];[[[Foo alloc] init] doSomethingElse];
The first sentence does not report an error, and the second sentence will report an error. If you change it:
+ (instancetype)buildInstance
Both of these two statements will report an error. Why?
Because in the first sentence, when the returned value of buildInstance is id, the compiler does not know who to consider the returned value, nor can it find the doSomethingElse method.
Init is treated as an instancetype returned by the compiler. convenience constructor does notOf course, there are many other benefits, so let's get started later.
Reprinted please indicate the blog from laruence: http://prevention.iteye.com