OC Basics-Construction Method ID type

Source: Internet
Author: User
Tags access properties

The new method implements the principle:

New has done three things.

1. Open storage space + Alloc method

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

3. Return the address of the object

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

Alloc:1. Opening up Storage 2. Set all properties to 0 3. Returns the address of the current instance object

Init:1. Initialize member variables, but by default the implementation of Init is nothing to do 2. Returns the initialized instance object address

Note: The address returned by Alloc, and the address that Init returns is the same address

Concepts and uses of construction methods:

The method that starts with Init in OC, which we call the construction method

Used to initialize an object so that an object is created with some properties and values

Override the Init method to initialize the member variable in the Init method:

Overriding the Init method must be rewritten in the format specified by Apple, and if it does not follow the rules, it will cause some unknown errors

1. The parent class must be initialized before the subclass is initialized

Subclasses inherit from parent class The child class has the parent class all member subclasses must call the parent class's constructor method to initialize the members.

2. Must determine if the parent class is initialized successfully, only the parent class initialization succeeds to continue initializing subclasses

To prevent the initialization method of the parent class, release the space that self points to and re-alloc a space. Also [Super init] may alloc fail, 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 recipients who call on behalf of WHO

- (instancetype) init {    //  1. Initializes the parent class if the parent class initializes successfully, the corresponding address is returned, and nil  nil = = is returned if the initialization fails       0 = = False = = Not initialized successfully self   = [Super init];    // 2. Determine if the parent class is initialized successfully   if       (Self! = Nil)         {      //  3. Initialize the subclass to set the value of the property to          6;   }    // 4. Return address   return      Self ; }                           

Simple version:

- (instancetype) init {     //  Note: do not write = = = =     must assign the return value of [Super init] toself    C6>if (self = [Super init]) {         //  Initialize subclass        6;    }     return      Self ; }            

Custom Construction methods:

The custom constructor method is actually customizing an init method:

1. Must be an object method

2. Be sure to return to Id/instancetype

3. Method name must begin with Init

#import "Person.h"@implementation Person//overriding the Init method-(instancetype) init{if(self =[Super Init]) {Self.name=@"Wang two small"; Self.age= A; }    returnSelf ;}//Custom Construction methods A class can have 0 or more custom construction methods-(Instancetype) Initwithname: (NSString *) name{if(self =[Super Init]) {_name=name; }    returnSelf ;}//a custom construction method can have 1 or more parameters-(Instancetype) Initwithname: (NSString *) name Andage: (int) age{if(self =[Super Init]) {_name=name; _age=Age ; }    returnSelf ;}@end

Custom construction methods are performed in inheritance:

Who declares the member to be initialized (the parent class attribute is given to the parent class to handle the subclass method to handle only its own unique properties)

#import "Student.h" @implementationStudent/*-(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 name and age properties are initialized by the constructor of the parent class    if(self =[Super Initwithname:name Andage:age]) {_studentno=Studentno; }    returnSelf ;}@end

Invoke Plot:

Custom class factory methods:

What is a class factory method:

Class methods for quickly creating objects, which we call class factory methods

The class factory method is primarily used to allocate storage space to objects and initialize this storage space

The custom class factory method is a specification for Apple, and in general we give a class A custom constructor method and a custom class factory method for creating an object

Specification:

1. Must be class method +

2. The method name begins with the name of the class, with the first letter lowercase

3. There must be a return value, the return value is Id/instancetype

Example:

[[NSString alloc] init]; [NSStringstring]; [[NSString Alloc] initwithstring: (NSString*)]; [NSString stringwithstring: (NSString*)];    [[Nsarray alloc] init];    [Nsarray array]; [Nsarray alloc] initwithobjects: (ID), ..., nil]; [Nsarray arraywithobjects: (ID), ..., nil];//Custom class factory methods+ (Instancetype) Personwithname: (NSString *) name Andage: (int) age{ person* Person =[[Person alloc] init]; Person.name=name; Person.age=Age ; returnPerson ;}

The custom class factory method takes note of the point in inheritance:

Because subclasses inherit all the methods and properties of the parent class by default, the class factory method is also inherited

Create an object in a class factory method do not use the class name to create it. Be sure to use self to create

Self represents a class object in a class method (who calls the current method and self represents)

The class factory method of the parent class is created with the class name of the parent class when the instance object is created, and if the child class calls the class factory method of the parent class to create the instance object, the instance object of the parent class is created

@interfacePerson:nsobject+ (ID) person;@end @implementation Person+ (ID) person{return[[Person alloc] init];}@end @interfaceStudent:person@property NSString*name;@end @implementationStudent@end intMainintargcConst Char*argv[]) {Student*stu = [Student person];//equivalent to [[Person alloc] init] needs to be [[Self alloc] init][Stu SetName:@"LNJ"];//error, because there is no setname in person} //Custom class factory methods use 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 ; returnPerson ;}

ID Type:

ID is a data type and is a Dynamic data type

Since it is a data type, it can be used to

1. Defining variables

2. Parameters as functions

3. The return value as a function

ID = = NSObject * Universal pointer

The 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 type of the variable is known at compile time,

Know what properties and methods are in the variable

These properties and methods can be accessed at compile time,

If you define a variable through a static data type, if you cannot access properties and methods that are part of a static data type, the compiler will error

Features of Dynamic Data types:

At compile time, the compiler does not know the true type of the variable, but only when it is run to know its true type.

If you define a variable through a dynamic data type, the compiler does not error if you access properties and methods that are not part of the Dynamic Data type

    • You cannot call a subclass-specific method by defining a variable with a static data type
    • You can call a subclass-specific method by defining a variable with a dynamic data type
    • A variable defined by a Dynamic data type can call a private method
      • Disadvantage: Because the Dynamic Data type can call any method, it is possible to call the method that does not belong to itself, and compile without error, so it may cause runtime errors
      • Scenario: polymorphic, can reduce the amount of code, avoid calling subclass-specific methods require coercion type conversion
    • To avoid runtime errors raised by Dynamic data types, in general, if a variable is defined with a dynamic data type, a decision is made to determine whether the current object can invoke the method before invoking the object's method
      • Iskindofclass
        ID New ];             // Iskindofclass, determines whether the specified object is a class, or is a subclass        of a class if class ] ]) {            [obj eat];        }    
      • Ismemberofclass
        ID New ];         if class ]]) {            ///  Ismemberofclass: Determines whether the specified object is an instance of the currently specified class             [obj eat        ]   ;

The difference between Instancetype and ID:

Instancetype = = ID = = Universal pointer = = Point to an object

ID cannot judge the true type of an object at compile time

Instancetype can determine the true type of an object at compile time.

(One does not know the real type at compile time, one knows the real type at compile time)

The ID can be used to define a variable, which can be a return value, as a formal parameter

Instancetype can only be used as a return value

It will perform type checking, and if the object is created, it will have a warning message to prevent errors if it is assigned an irrelevant object.

Note: After any custom construction method, the return value uses Instancetype as far as possible, do not use the ID

OC Basics-Construction Method ID type

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.