[]self Init]

Source: Internet
Author: User

This code was encountered in the dictionary-to-model:

1#import"HMAppInfo.h"2 3 @implementation Hmappinfo4 5-(Instancetype) Initwithdict: (Nsdictionary *) Dict6 {7     //Self is the object8Self =[Super init];9     if(self) {Ten         //assign a value to a property in a dictionary, all the methods related to the Plist key value are here!  OneSelf.name = dict[@"name"]; ASelf.icon = dict[@"icon"]; -     } -     returnSelf ; the } -  -+ (Instancetype) appinfowithdict: (Nsdictionary *) Dict - { +     //Self is class -     return[[Self alloc] initwithdict:dict]; + } A  at@end

In line 8th, there's a

Self = [super init];

Some do not understand, in fact, this is their own method of initializing the object caused by the ignorance.
Searched for some technical articles under reference:
[Obj-c notes] "Self = [super init]" explanation and hidden bug

Objective-c's recommended Init method is as follows:

1 - (ID) init2{3     if(self = [super init])4      {5         // Add properties to subclass for initialization 6    }  7     return self ; 8 }

Here are a few questions,

1. The role of [Super Init]:

The object-oriented embodiment, first uses the parent class's Init method to initialize the parent class part property of the subclass instance.

2. Why should self be assigned a value of [Super init]:

Simply to prevent the parent class from initializing the method to release the space that self points to and re-alloc a space. At this point, [super init] may fail alloc, then the statement in if is no longer executed.

3. Super as the essence of the message recipient:

super is not really a pointer, and the essence of [super message] is to accept the parent's message by self. It is important to note that in [Super message], the message method appears as self in the [Super message] context, that is, the subclass instance.

Hidden bugs:

Suppose there is a parent class aobj and a subclass bobj.

When Aobj's Init method is as follows:

- (ID) init{    = self ;     = [Aobj alloc];    [TMP release];     // Other staffs    return Self ;}

The Init method for Bobj is as follows:

- (ID) init{    if(self = [super init])    {        //otherstaffs     }     return Self ;}

Note In line 5th , [self class] obtains the class instance corresponding to the instance that the self points to, in this case bobj. Thisway, the INI T method of any subclass of Aobj is guaranteed to be secure.

if (self = [super init]) This is a usual suggested notation, assigning and measuring 0 only to prevent the superclass from changing during initialization, returning different objects, Why must Super Alloc?

As we all know, Objective-c is an object-oriented language, in general, when we define a class in objective-c, we always provide an initialization method, which is generally written by everyone:

1-(MyClass *) Init2 3 {4 5Self =[Super init];6 7     if(self) {8 9          //perform initialization of some resources and variablesTen  One     } A  -         returnSelf ; -  the}

This is a simple code, but there are a lot of things to think about:

1. Why should I invoke the initialization method of the parent class through [super Init] and what is being done in the initialization method of the parent class?

First of all, we know the concept of object inheritance, a subclass inherits from the parent class, but also to implement all the functions of the parent class, this is the is-a relationship, such as the dog is a mammal, then the dog must have the characteristics and functions of mammals. Therefore, in the initialization method of the subclass, you must first call the parent class's initialization method to implement the initialization of the parent class related resources. For example, when we initialize a dog, we must first initialize the Mammal object and give the result to the dog, so that the dog satisfies the characteristic of the mammal.

Typically, under iOS, all classes inherit from NSObject, and NSObject's Init method is simple, which is return self. When the initialization of the parent class is complete, that is, self is not nil, you can begin the initialization of the subclass.

2, whether must provide initialization method, whether must use Init as initialization method?

We create an object in objective-c typically using the

MyClass *newclass = [[MyClass alloc] init];

Or

MyClass *newclass = [Myclass new];  

The new method is a static method of the NSObject object, which, according to Apple's documentation, is actually a combination of the Alloc and Init methods, in fact the two are the same, but Apple still recommends that we use the first method, why? Because using the first method, you can use your own Init method to do some initialization (with your own written init***** method), of course, if the subclass does not provide the Init method, the natural call is the parent class Init method. So, from a security point of view, as a developer we must initialize the object before the object is used, so be sure to provide an initialization method when defining the class. But are you sure you want to use Init as the method name? The answer is not necessarily. Using init as the method name is just a rewrite of the NSObject init method, and if you redefine an initialization method yourself, it is perfectly possible, as long as you remember to invoke the new defined initialization method when you use it.

However, this approach is not advisable from a design standpoint. In terms of reusability, if it is necessary to define some initialization methods that accept different parameters, my suggestion is to first define a common method of init, and then call it in other methods, such as:

- (ID)   Common method of init init {    = [Super init];      if (self) {              }    return to self ;} -(ID) initwithstring: (NSString *) astring{    [self init];     = astring;  }   -(ID) initwithimage: (UIImage *) aimage{    [self init];     = aimage;  }

Add:

In object-oriented programming, if you write a class without a constructor, the class can compile and work perfectly. If the class does not provide an explicit constructor, the compiler provides you with a default constructor function. In addition to creating the object itself, the only function of the default constructor is to call its superclass's constructor. In many cases, this superclass is part of the language framework, such as the object class in Java and the NSObject class in Objective-c.

In either case, having at least one constructor in a class is a good programming practice, and if there are attributes in the class, it is often good practice to initialize those properties.

[]self Init]

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.