Construction method
1. Principle of object creation
New Split two-part song
Person *p = [Person alloc]; Allocating memory (+ALLOC)
Person *p = [P init]; Initialize (-init)
Merge: Person *p = [[Person alloc] init];
Rewrite of the 2.init method
-(void) init { if(self = [Super init]) { ten; You want the member variable to have some default value immediately after the object is created } return self ;
3. Custom Construction methods
/** Custom Construction method One **/- (ID) Initwithage: (int) Age {if(self =[Super Init]) {_age=Age ; } returnSelf ;}/** Custom Construction Method II **/- (ID) Initwithage: (int) Age Andno: (int) No {if(self =[Super Init]) {_age=Age ; _no=No; } returnSelf }/** Note **///The return value is the ID type//method names start with Init
Classification
Category
You can extend some methods to a class (without modifying the original code)
#import " Person.h " @interface Person (Hy)-(void) show; @end /* * statement * */ // @interface class names (category name) // @end
#import " Person+hy.h " @implementation Person (Hy)-(void) show { NSLog (@ " hahaha ~~! " );} @end /* * Implementation * */ // @implementation class names (category name) // @end
Use Note:
Categories can only increment methods cannot increase member variables
Member variables declared in the original class can be accessed in the classification method implementation
Classification can be re-implemented in the original class method but will overwrite the original method will cause the original method can no longer use
Priority of Method Invocation: Classification (the last category that participates in the compilation takes precedence)---> Original class---> Parent class
In-depth study of classes
The class itself is also an object of type class object
Person *p = [[Person alloc] init];
Class C = [P class];
[C test];//c is a class method that can invoke the person inside
Classes are loaded and initialized:
When the program starts, it loads all classes and classifications in the project, and the +load method that calls each class and category after it is loaded will only be called once
The +initialize method of the current class is called when a class is first used
First load the parent class and then load the subclass (call the +load method of the parent class before calling the +load method of the subclass) first initialize the parent class and then initialize the subclass (call the +initialize method of the parent class before calling the +initialize method of the child class)
Further study on classification of objective-c structural methods