黑馬程序員---OC學習筆記之autorelease快速創建對象的應用

------Java培訓、Android培訓、iOS培訓、.Net培訓--------

【要求】創建一個學生對象,要求快速創建,並初始化年齡爲指定的值

 

例如:在student類實現中,自定義以下兩個方法:

//初始化年齡
-(instancetype)initWithAge:(int)age{
    if (self = [super init]) {
        self.age = age;
   }
    return self;
}
 
+(instancetype)studentWithAge:(int) age{
    //快速創建對象,並管理內存
    return [[[Student alloc] initWithAge:age]autorelease];
}
-(void)dealloc{
   
    NSLog(@"This Student dead....");
    [super dealloc];
}
 

 

在main.m文件中

    @autoreleasepool {
        Student *st = [Student studentWithAge:24];
        NSLog(@"student age =%d",st.age);
   }


打印結果:

2015-10-06 21:51:18.087 MRCDemo[3265:303] student age= 24

2015-10-06 21:51:18.089 MRCDemo[3265:303] This Studentdead....

2015-10-06 21:51:18.090 MRCDemo[3265:303] This persondead....

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章