OC basics-constructor id type, oc Constructor

Source: Internet
Author: User

OC basics-constructor id type, oc Constructor

Implementation principle of the new method:

New has done three things.

1. Open up the bucket + alloc Method

2. Initialize all attributes (member variables)-init Method

3. Return the object address

[Person new]; = [[Person alloc] init];

Alloc: 1. Open a bucket 2. Set all attributes to 0 3. Return the address of the current instance object

Init: 1. initialize the member variable, but the init implementation does not do anything by default. 2. Return the address of the initialized instance object.

Note: The address returned by alloc is the same as the address returned by init.

Concepts and usage of constructor:

Methods Starting with init in OC are called constructor methods.

Used to initialize an object so that an object can have certain attributes and values as soon as it is created.

Override the init method and initialize the member variable in the init method:

The init method must be rewritten according to the format specified by Apple. Otherwise, some unknown errors may occur.

1. You must initialize the parent class before initializing the subclass.

If the subclass inherits from the parent class, then the subclass has all the member subclasses of the parent class. The subclass must call the constructor of the parent class to initialize these members.

2. You must determine whether the parent class is initialized successfully. Only when the parent class is initialized successfully can the child class continue to be initialized.

In order to prevent the parent class's initialization method from dropping the space pointed to by self and re-alloc a space. In addition, the [super init] may fail alloc, and then the statement in if is no longer executed.

3. Return the address of the current object

Super and self point to the same message receiver, that is, who calls the message.

-(Instancetype) init {// 1. if the initialization of the parent class is successful, the corresponding address is returned. If the initialization fails, nil = 0 = false = not initialized successfully self = [super init]; // 2. determine whether the parent class is successfully initialized if (self! = Nil) {// 3. initialize the subclass to set the attribute value _ age = 6;} // 4. return address return self ;}

Lite version:

-(Instancetype) init {// Note: Do not set = To =. Always assign the value of [super init] to self if (self = [super init]). {// initialize subclass _ age = 6;} return self ;}

Custom constructor:

The custom constructor is actually a custom init method:

1. It must be an object method.

2. The id/instancetype must be returned.

3. The method name must start with init

# Import "Person. h "@ implementation Person // rewrite the init method-(instancetype) init {if (self = [super init]) {self. name = @ "Wang erxiao"; self. age = 12;} return self;} // custom constructor a class can have 0 or more custom constructor-(instancetype) initWithName :( NSString *) name {if (self = [super init]) {_ name = name;} return self;} // The Custom constructor can have one or more parameters-(instancetype) initWithName :( NSString *) name andAge :( int) age {if (self = [super init]) {_ name = name; _ age = age;} return self;} @ end

The custom constructor is represented in inheritance:

Who initializes the declared members (the attributes of the parent class are handed over to the parent class to process the subclass method and only process its own unique attributes)

# Import "Student. h "@ implementation Student/*-(instancetype) initWithStudentNO :( NSString *) studentNO andName :( NSString *) name andAge :( int) age {if (self = [super init]) {self. name = name; self. age = age; self. studentNO = studentNO;} return self;} */-(instancetype) initWithStudentNO :( NSString *) studentNO andName :( NSString *) name andAge :( int) age {// The parent class constructor initializes the name and age attributes if (self = [super initWithName: name andAge: age]) {_ studentNO = studentNO ;} return self;} @ end

Call illustration:

Custom factory method:

What is a factory-like method:

Class methods used to quickly create objects are called class factory methods.

The class factory method is mainly used to allocate a bucket to the object and initialize the bucket.

The custom class factory method is Apple's specification. Generally, we provide a custom constructor and custom class factory method for a class to create an object.

Specifications:

1. It must be a class method +

2. The method name starts with the class name and starts with lowercase letters

3. There must be a return value. The return value is id/instancetype.

Example:

[[NSString alloc] init]; [NSString string]; [[NSString alloc] initWithString :( NSString *)]; [NSString stringWithString :( NSString *)]; [[NSArray alloc] init]; [NSArray array]; [NSArray alloc] initWithObjects :( id ),..., nil]; [NSArray arrayWithObjects :( id ),..., nil]; // custom class factory method + (instancetype) personWithName :( NSString *) name andAge :( int) age {Person * person = [[Person alloc] init]; person. name = name; person. age = age; return person ;}

Note the following points in inheritance:

By default, subclass inherits all methods and attributes of the parent class, so the class factory method will also be inherited.

Do not use the class name to create an object in the class factory method. You must use self to create the object.

Self indicates the class object in the class method (who calls the current method, self indicates who)

The class factory method of the parent class is created using the class name of the parent class when creating the instance object. If the subclass calls the class factory method of the parent class to create the instance object, the created instance object is the parent class.

@ Interface Person: NSObject + (id) person; @ end @ implementation Person + (id) person {return [[Person alloc] init];} @ end @ interface Student: person @ property NSString * name; @ end @ implementation Student @ end int main (int argc, const char * argv []) {Student * stu = [Student person]; // equivalent to [[Person alloc] init], which must be [[self alloc] init] [stu setName: @ "lnj"]; // an error is returned, because there is no setName} In Person // The Custom class factory method uses self instead of class name + (instancetype) personWithName :( NSString *) name andAge :( int) age {// Person * person = [[Person alloc] init]; Person * person = [[self alloc] init]; person. name = name; person. age = age; return person ;}

Id type:

Id is a data type and a dynamic data type.

Since it is a data type, it can be used

1. Define Variables

2. As a function parameter

3. As the return value of the Function

Id = NSObject * universal pointer

Difference between id and NSObject:

NSObject * is a static data type

Id is a dynamic data type

By default, all data types are static data types.

Characteristics of static data types:

The variable type is known during compilation,

Know the attributes and methods in the Variable

These attributes and methods can be accessed during compilation,

If a variable is defined by a static data type and the attribute and method of the static data type cannot be accessed, the compiler reports an error.

Features of dynamic data types:

During compilation, the compiler does not know the true type of the variable. It only knows the true type of the variable at runtime.

If you use a dynamic data type to define variables and access attributes and methods that are not of the dynamic data type, the compiler will not report an error.

  • Variables are defined using static data types, and the unique methods of sub-classes cannot be called.
  • You can call a method unique to a subclass by defining variables in a dynamic data type.
  • You can call private methods through variables defined by dynamic data types.
    • Disadvantages: dynamic data types can call any method, so it is possible to call a method that is not your own, but will not report errors during compilation, so it may cause runtime errors.
    • Application Scenario: Polymorphism can reduce the amount of code and avoid forced type conversion when calling the method specific to the subclass.
  • To avoid running errors caused by dynamic data types, if a variable is defined using a dynamic data type, a judgment is made before the method of the object is called, determine whether the current object can call this method
    • IsKindOfClass
Id obj = [Student new]; // isKindOfClass to determine whether the specified object is a class or a subclass of a class if ([obj isKindOfClass: [Student class]) {[obj eat];}
    • IsMemberOfClass
Id obj = [Student new]; if ([obj isMemberOfClass: [Student class]) {// isMemberOfClass: determines whether the specified object is an instance of the currently specified class [obj eat];}

Differences between instancetype and id:

Instancetype = id = universal pointer = point to an object

The id cannot determine the actual object type during compilation.

Instancetype can be used to determine the actual object type during compilation.

(One does not know the actual type during compilation, and the other does know the actual type during compilation)

Id can be used to define variables, return values, and form parameters.

Instancetype can only be used as the return value

It checks the type. If the created object is assigned an irrelevant value, a warning is generated to prevent errors.

Note: in the future, if you use a custom constructor, try to use instancetype for the returned value. Do not use id.

 

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.