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

实现-(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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值