IOS Dev (48) initializer and convenience constructor

Source: Internet
Author: User

IOS Dev (48) initializer and convenience constructor

  •  
  • Initializer

    You should be familiar with this.

    - (id)initWithSomething;
    Convenience constructor

    However, 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 not

    Of course, there are many other benefits, so let's get started later.

    Reprinted please indicate the blog from laruence: http://prevention.iteye.com

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.