浅谈Objective-C构造函数

移动开发 iOS
本文主要介绍了Objective-c使用构造函数来初始化函数并调用函数的内容,很详细讲解了函数的构造,先来看详细内容。

Objective-C构造函数是本文呢要介绍的内容,在objective-c中我们与使用很多其他的oop语言一样,可以使用构造函数,他是在创建对象的时候用来初始化对象数据的一种特殊的方法。构造函数可以使用任何方式命名,但是通常,将他们命名为Init。

构造方法返回对象的一个指针,我们可以通过调用超类的init方法来获取这个指针(超类是当前的类所派生自的类,也就是当前类的父类,这里通常是NSObject类);

参考代码:

-(Container * ) myInit(int)n  
{  
   self = [super init];  
   if(self)  
  {  
         [self  setNumber:n];  
   }  
    return selef;  

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

在代码中,当我们创建对象的时候,就可以把值传递给构造方法。例如,如下面的代码把对象中的数据初始化为:3

Container* obj = [[Container new] myInit:3]; 
  • 1.

下面是一个完整的例子的参考代码:

#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];// 这里的超类的Init方法的名称是不能改变的  
 
    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[]) {  
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];  
    myobj* obj = [[myobj new] myinit:10:20];  
    [obj outP];  
    [pool drain];  
    return 0;  

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.

在Console窗口中的运行结果如下所示:

run  
[Switching to process 643]  
Running…  
this is the number you put in =30 
Debugger stopped.  
Program exited with status value:0. 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

小结:浅谈Objective-C构造函数的内容介绍完了,希望本文对你有所帮助。更多Objective-C关于的内容,请参考编辑推荐。

责任编辑:zhaolei 来源: 互联网
相关推荐

2011-08-17 10:58:59

Objective-C构造函数

2011-08-15 17:29:36

Objective-C构造函数

2011-08-02 13:16:36

Objective-C 语法 函数

2011-08-03 16:55:05

Objective-C 代理

2011-08-04 09:35:09

Objective-C 编码规范

2011-08-03 15:51:48

Objective-C 协议 委托

2011-07-28 18:11:18

Objective-C Cocoa 编程

2011-08-01 17:11:43

Objective-C 函数

2011-08-10 18:07:29

Objective-C反射

2013-06-20 10:40:32

Objective-C实现截图

2013-03-27 12:54:00

iOS开发Objective-C

2011-05-11 11:20:26

Objective-C

2011-05-11 15:58:34

Objective-C

2011-08-04 14:58:37

Objective-C Cocoa NSString

2011-05-11 13:54:08

Objective-C

2011-05-11 15:45:50

内存管理Objective-C

2013-08-21 14:57:42

objective-c问题

2011-05-11 14:06:49

Objective-C

2014-06-25 14:02:59

Objective-CKVO

2014-04-30 10:16:04

Objective-CiOS语法
点赞
收藏

51CTO技术栈公众号