zoukankan      html  css  js  c++  java
  • 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];
        }
    }
    
    @end
    
    int 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;
        }
    }
    
    @end
    
    int 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;
    }
    
  • 相关阅读:
    Beta冲刺 (6/7)
    Beta冲刺(5/7)
    Beta 冲刺 (4/7)
    Beta 冲刺 (3/7)
    软件产品案例分析(团队)
    Beta 冲刺 (2/7)
    Beta 冲刺 (1/7)
    java 常用设计模式及Spring中应用了哪些设计模式
    java 八大排序算法
    记录java学习计划及相关工作中用到的技术/工具
  • 原文地址:https://www.cnblogs.com/csutanyu/p/3782953.html
Copyright © 2011-2022 走看看