重写构造方法实现两种功能

来源:互联网 发布:股票行情软件免费下载 编辑:程序博客网 时间:2024/06/10 05:01

        • 实现-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.mimport "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.mimport "Student.h"@implementation Student-(instancetype)init{    if (self = [super init]){        _age = 10;   //设置该变量的默认值    }    return self; }@end
0 0