浅谈Objective-C构造函数

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

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

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

参考代码:

  1. -(Container * ) myInit(int)n  
  2. {  
  3.    self = [super init];  
  4.    if(self)  
  5.   {  
  6.          [self  setNumber:n];  
  7.    }  
  8.     return selef;  

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

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

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

  1. #import <Foundation/Foundation.h> 
  2. #import "student.h"  
  3. @interface  myobj:NSObject  
  4. {  
  5.     int number;  
  6. }  
  7. -(void) setNumber:(int)Num:(int) Num2;  
  8. -(void) outP;  
  9. -(myobj*) myinit:(int)Num:(int)Num2;  
  10. @end  
  11. @implementation myobj  
  12. {  
  13. }  
  14. -(myobj*) myinit:(int)Num:(int)Num2  
  15. {  
  16.     self =[super init];// 这里的超类的Init方法的名称是不能改变的  
  17.  
  18.     if (self) {  
  19.         [self setNumber:Num:Num2];  
  20.     }  
  21.     return self;  
  22. }  
  23. -(void) setNumber:(int)Num:(int)Num2{  
  24.     number = Num+Num2;  
  25. }  
  26. -(void) outP{  
  27.     printf("this is the number you put in =%i",number);  
  28. }  
  29. @end  
  30. int main (int argc, const char * argv[]) {  
  31.     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];  
  32.     myobj* obj = [[myobj new] myinit:10:20];  
  33.     [obj outP];  
  34.     [pool drain];  
  35.     return 0;  

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

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

小结:浅谈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-04 09:35:09

Objective-C 编码规范

2011-08-03 16:55:05

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反射

2011-05-11 15:58:34

Objective-C

2013-03-27 12:54:00

iOS开发Objective-C

2011-05-11 11:20:26

Objective-C

2013-06-20 10:40:32

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

2011-05-11 14:06:49

Objective-C

2013-08-21 14:57:42

objective-c问题

2012-06-15 09:47:48

Objective-CCategory

2014-04-30 10:16:04

Objective-CiOS语法
点赞
收藏

51CTO技术栈公众号