Objective-C ConstructorThe content to be introduced in this article is as follows:Objective-cWe can useConstructorIt is a special method used to initialize object data when creating an object.ConstructorYou can name them in any way, but generally, they are named Init.
ConstructorReturns a pointer to an object. We can call the init method of the superclass to obtain that the pointer superclass is the class derived from the current class, that is, the parent class of the current class, here is generally the NSObject class );
Reference code:
- -(Container * ) myInit(int)n
- {
- self = [super init];
- if(self)
- {
- [self setNumber:n];
- }
- return selef;
- }
In code, when we create an object, we can pass the value to the constructor. For example, the following code initializes the data in the object to: 3
- Container* obj = [[Container new] myInit:3];
The following is the reference code for a complete example:
- # 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;
- }
The running result in the Console window 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:Objective-C ConstructorI hope this article will help you. MoreObjective-CFor more information, see edit recommendations.