A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© luronghua 中级黑马   /  2016-7-18 23:26  /  1240 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

自定义构造方法。

一、构造方法

展示一个例子来说明一下:


[html] view plain copy
#import "Student.h"  
int main(int argc, const char * argv[])  
{  
    @autoreleasepool {  
        Student *stu = [[Student alloc] init];//调用Student的alloc方法分配内存,然后再调用init方法初始化对象  
        stu.age = 10;      
        [stu release];  
    }  
    return 0;  
}  
上例中像init这样用来初始化对象的方法,就是一种构造方法。
二、自定义构造方法

默认的构造方法,也就是init方法,它是不接收任何参数的。因此,在实际开发中,需要自定义构造方法。
接下来举例,自定义一个构造方法,可以传入一个age参数来初始化Student对象。

1)需要在Student.h中添加方法声明


[objc] view plain copy
- (id)initWithAge:(int)age;  
上例中的
a. id可以代表任何OC对象

b. 这个构造方法接收一个int类型的age参数,目的是在初始化Student对象时
2)需要在Student.m中定义构造方法


[objc] view plain copy
- (id)initWithAge:(int)age {  
    self = [super init];//调用父类的构造方法,它会返回初始化好的Student对象,这里把返回值赋值给了self,self代表Student对象本身  
    if ( self ) {  
        _age = age;  
    }//如果self不为nil,给成员变量_age进行赋值  
    return self;//最后返回初始化过后的self  
}  
3)调用构造方法

[objc] view plain copy
Student *stu = [[Student alloc] initWithAge:10];//调用了构造方法initWithAge:,并传入10作为参数,因此Student对象的成员变量_age会变为10  
NSLog(@"age is %i", stu.age);//打印Student的成员变量_age,打印结果:  
[stu release];  
4)输出结果

age is 10

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马