代码改变世界

autorelease应用

2016-12-13 10:03  supper_Ho  阅读(143)  评论(0编辑  收藏  举报

//

//  main.m

//  02-autorelease应用

//

//  Created by apple on 14-3-18.

//  Copyright (c) 2014年 apple. All rights reserved.

//

 

#import <Foundation/Foundation.h>

#import "Chief.h"

 

 

int main(int argc, const char * argv[])

{

 

    @autoreleasepool {

    

        /*

        Chief * chi  = [[Chief alloc] init];

        Food * food = [chi makeFood];;

 

        

        NSLog(@"%@",food.name);//[nil name];

        

        [chi release];

        */

        

 

        

        Chief * chi = [Chief chief];

        Food * food = [chi chiefMakeFood];

        

        NSLog(@"%@",food.name);

        

        NSString * name = [NSString stringWithFormat:@"%@",@"施瓦辛格"];//都是autorelease

 

        NSLog(@"%@",name);

        

    }

    return 0;

}

 

 

 

//

//  Chief.m

//  01-autorelease基本概念

//

//  Created by apple on 14-3-18.

//  Copyright (c) 2014年 apple. All rights reserved.

//

 

#import "Chief.h"

 

@implementation Chief

 

- (void)dealloc

{

    [super dealloc];

    NSLog(@"厨师被回收了");

}

 

+ (Chief *)chief

{

    /*

    Chief * chi = nil;

    

    chi = [[Chief alloc] init];

    

//    [chi release];

    [chi autorelease];

    */

    

    Chief * chi = [[self alloc] init];

    

    

    return [chi autorelease];

}

- (Food *)chiefMakeFood

{

   

  

    //如果在方法中创建一个对象,最好给我初始化为nil,防止出现野指针错误

    // 1

    Food * food = [[Food alloc] init];

    food.name = @"凑豆乳";

//    // 0

//    [food release];

    [food autorelease];

    

    return food;

    

}

 

@end