Objective-C ConstructorIs the content to be introduced in this article, mainly to understandConstructorIt is a special method used to initialize object data when an object is created. The constructor returns a pointer to the object. We can call the init method of the superclass to obtain this pointer.Objective-cFunction,Objective-C Constructor,Objective-CFunction call,Objective-CFunction declaration.
Constructor is a special method used to initialize object data when creating an object. Constructors can be named in any way, but usually they are named Init. The constructor returns a pointer to an object. We can call the init method of the superclass to obtain this pointer. The superclass is the class derived from the current class, that is, the parent class of the current class, this is generally the NSObject class.
Objective-C Constructor
Reference content is as follows:
- -(Container * ) myInit(int)n {
- self = [super init];
- if(self) {
- [self setNumber:n];
- }
- return selef;
- }
In the Code, when we create an object, we can pass the value to the constructor method). The following code initializes the data in the object to 3.
Reference content is as follows:
- Container* obj = [[Container new] myInit:3];
Complete instance reference code
Reference content is as follows:
- # Import <Foundation/Foundation. h>
- # Import "student. h"
- @ Interface myobj: NSObject {
- Int number;
- }
- -(Void) setNumber :( int) Num :( int) Num2;
- -(Void) outP;
- -(Myobj *) myinit :( int) Num :( int) Num2;
- @ End @ implementation myobj {}
- -(Myobj *) myinit :( int) Num :( int) Num2 {
- Self = [super init];
- // The Name Of The superclass Init method cannot be changed.
- If (self ){
- [Self setNumber: Num: Num2];
- }
- Return self;
- }
- -(Void) setNumber :( int) Num :( int) Num2 {
- Number = Num + Num2;
- }
- -(Void) outP {
- Printf ("this is the number you put in = % I", number );
- } @ End int main (int argc, const char * argv []) {
- NSAID utoreleasepool * pool = [[NSAID utoreleasepool alloc] init];
- Myobj * obj = [[myobj new] myinit: 10: 20];
- [Obj outP];
- [Pool drain];
- Return 0;
- }
Running results in the Console window:
Reference content is as follows:
- run [Switching to process 643]
- Running…
- this is the number you put in =30
- Debugger stopped.
- Program exited with status value:0.
Summary: The Objective-C constructor has been described in detail. I hope this article will help you!