您的位置:首页 > 职场人生

【黑马程序员】重写构造方法实现两种功能

2015-08-23 13:58 381 查看
——Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ——-

实现-instancetypeinitWithXXXintage

要求使每个新创建出来的对象都有一个自定义的默认值

实现-(instancetype)initWithXXX:(int)age;

思考&实现:创建一个学生类Student,通过重写构造方法实现创建学生对象的时候,默认的年龄的值为指定的年龄

student.h

#import <Foundation/Foundation.h>
@interface Student : NSObject
@property (nonatomic, assign)int age;
-(instancetype) initWithAge:(int)age;
+(instancetype)studentAgeWith:(int)age;
@end


Student.m

import "Student.h"
@implementation Student
-(void)dealloc{
NSLog(@"Student 被释放");
[super dealloc];
}

//自定义构造方法
-(instancetype) initWithAge:(int)age{
if (self = [super init]){
_age = age;
}
return self;
}

//自定义初始化方法
+(instancetype)studentAgeWith:(int)age{
return [[[self alloc] initWithAge:age]autorelease];
}
@end


main.m

#import <Foundation/Foundation.h>
#import "Student.h"

int main(int argc, const char * argv[]){
@autoreleasepool{
Student * stu = [[[Student alloc]initWithAge:10]autorelease];
Student *stu1 = [Student studentWithAge:100];
NSLog(@"stu.age = %d, stu1.age = %d", stu.age, stu1.age);

}
reutrn 0;
}


要求使每个新创建出来的对象都有一个自定义的默认值

student.h

#import <Foundation/Foundation.h>
@interface Student : NSObject
@property (nonatomic, assign)int age;
@end


Student.m

import "Student.h"
@implementation Student
-(instancetype)init{
if (self = [super init]){
_age = 10;   //设置该变量的默认值
}
return self;
}
@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: