【Lession 12 OC语言】- 内存管理3 -autorelease

本节目录

 

autorelease

添加了autorelease后就不用再用release代码,它会自己释放

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

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        
        Book *book = [[[Book alloc] init] autorelease];
        
      }
    return 0;
}

可以看到程序运行结束会Book被销毁

2014-03-18 18:11:20.808 HellowWord_OC[1499:303] Book 被销毁

 

如果没有再auorelease,Book被销毁不会被打印出来,说明这个对象没有被销毁

 

静态创建实例

Book.h

#import <Foundation/Foundation.h>

@interface Book : NSObject

@property(nonatomic,assign)double price;

+(id )book;

+(id)bookWithPrice:(double)price;

@end

Book.m

#import "Book.h"

@implementation Book

+(id)book{
    return [[[Book alloc] init] autorelease];
}


+(id)bookWithPrice:(double)price{
    //Book *book = [[[Book alloc] init] autorelease];
    //Book *book = [self book];self指类名
    Book *book = [Book book];
    book.price = price;
    return book;
}

-(void)dealloc{
    NSLog(@"Book 被销毁");
    [super dealloc];
}

 

猜下有几个销毁代码?

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

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        
        Book *book = [[[Book alloc] init] autorelease];
       
        //自定释放,不用添加relase代码
        Book *book1 = [Book book];
        
        //自定释放,不用添加relase代码
        Book *book2 = [Book bookWithPrice:12.50];
        
        Book *book3 = [[Book alloc] init];
        
      }
    return 0;
}

 

总结:实例化对象时,是用alloc的方法的就要进行添加autorealese或者release代码

   通过静态方法实例化的不用添加autorealese或者release代码

posted @ 2014-03-18 18:13  Vincent_Guo  阅读(193)  评论(0编辑  收藏  举报