首页 > 代码库 > Objc中2维指针作为输出参数时由ARC及@autoreleasepool引发的血案
Objc中2维指针作为输出参数时由ARC及@autoreleasepool引发的血案
先看下面一个例子
#import <UIKit/UIKit.h>#import "AppDelegate.h"@interface Something : NSObject- (void)doWithError:(NSError **)outError;@end@implementation Something- (void)doWithError:(NSError **)outError{ @autoreleasepool { *outError = [NSError errorWithDomain:@"Emergency" code:999 userInfo:nil]; }}@endint main(int argc, const char *argv[]){ @autoreleasepool { NSError *error = nil;
// Sometimes EXC_BAD_ACCESS when return from this method. [[[Something alloc] init] doWithError:&error]; // At this point, the main thread gives EXC_BAD_ACCESS. NSLog(@"%@", error); } return 0;}
在NSLog输出的时候会EXC_Bad_ACCESS
正确写法应该是这样:
@interface Something : NSObject- (void)doWithError:(NSError **)outError;@end@implementation Something- (void)doWithError:(NSError **)outError{ NSError *error = nil; @autoreleasepool { error = [NSError errorWithDomain:@"Emergency" code:999 userInfo:nil]; // Do something } if(error) { *outError = error; }}@endint main(int argc, char * argv[]){ @autoreleasepool { NSError *__autoreleasing error = nil; [[[Something alloc] init] doWithError:&error]; // At this point, the main thread gives EXC_BAD_ACCESS. NSLog(@"%@", error); int a = 1; ++a; } return 0;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。