生活随笔
收集整理的這篇文章主要介紹了
autoreleasing的用法介绍:
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
在c/c++,objective-c內存管理中有一條是:誰分配誰釋放。 __autoreleasing則可以使對像延遲釋放。比如你想傳一個未初始化地對像引用到一個方法當中,在此方法中實始化此對像,那么這種情況將是__autoreleasing表演的時候。看個示例: - (void) generateErrorInVariable:(__autoreleasing NSError **)paramError{ NSArray *objects = [[NSArray alloc] initWithObjects:@"A simple error", nil]; NSArray *keys = [[NSArray alloc] initWithObjects:NSLocalizedDescriptionKey, nil]; NSDictionary *errorDictionary = [[NSDictionary alloc] initWithObjects:objects forKeys:keys]; *paramError = [[NSError alloc] initWithDomain:@"MyApp" code:1 userInfo:errorDictionary]; } -(void)test { NSError *error = nil; [self generateErrorInVariable:&error]; NSLog(@"Error = %@", error); } 復制代碼 被編譯器翻譯后就變?yōu)?#xff1a; -(void)test { NSError *error = nil; NSError * __autoreleasing tmp = error; [self generateErrorInVariable:&tmp]; error = tmp; NSLog(@"Error = %@", error); } 復制代碼 這樣即便在函數內部申請的空間,在函數外部也可以使用,同樣也適合誰分配誰釋放的原則。 同樣下面的代碼也是類似原因, 只不過在沒有開啟ARC的情況下適用: -(NSString *)stringTest { NSString *retStr = [NSString stringWithString:@"test"]; return [[retStr retain] autorelease]; } 復制代碼 開啟ARC后,應改為:經過測試下面這種方法是可行的,不過都不建意這樣寫代碼, __autoreleasing官網的例子是用在傳引用參數當中(像上面那個NSError)。所以最好不要像下面這樣用 -(NSString *)stringTest { __autoreleasing NSString *retStr = [NSString alloc] initWithString:@"test"]; return retStr; } - (NSString *)stringTest __attribute__((ns_returns_autoreleased)){ NSString *retStr = [NSString alloc] initWithString:@"test"];return retStr;} 復制代碼 與上面功能相似。返回一個autorelease。 關于methord family, 如果方法名是以alloc, init, copy, mutablecopy,new字符開頭的,那么它們的返回值會被retain的,其它的默認就是autorelease返回的。下面介紹一下返回值的例子: - (id) foo __attribute((ns_returns_retained)); //返回值retain +1, init,new,alloc,copy,mutablecopy default are this - (id) foo __attribute((ns_returns_not_retained)); //返回指針弱引用, - (id) foo __attribute((ns_returns_autoreleased)); //返回autorlease, except default, are this 復制代碼 init開頭的方法有一個規(guī)定,一定要返回id或父類,子類的指針,不然要有warning. 這兒是原話: init methods must be instance methods and must return an Objective-C pointer type. Additionally, a program is ill-formed if it declares or contains a call to an init method whose return type is neither id nor a pointer to a super-class or sub-class of the declaring class (if the method was declared on a class) or the static receiver type of the call (if it was declared on a protocol). 復制代碼 當然你也可以打破這個規(guī)定,如果你這樣聲明方法: - (void)initStr __attribute__((objc_method_family(none))); 復制代碼 那么就是正確的。
轉載于:https://www.cnblogs.com/zsw-1993/p/4879685.html
總結
以上是生活随笔 為你收集整理的autoreleasing的用法介绍: 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。