本節目錄atom
添加了autorelease後就不用再用release代碼,它會本身釋放spa
#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被銷燬code
2014-03-18 18:11:20.808 HellowWord_OC[1499:303] Book 被銷燬
若是沒有再auorelease,Book被銷燬不會被打印出來,說明這個對象沒有被銷燬對象
Book.hblog
#import <Foundation/Foundation.h> @interface Book : NSObject @property(nonatomic,assign)double price; +(id )book; +(id)bookWithPrice:(double)price; @end
Book.mit
#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]; }
猜下有幾個銷燬代碼?io
#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代碼class
經過靜態方法實例化的不用添加autorealese或者release代碼import