【问题标题】:IOS block not working, giving error:EXC_BAD_ACCESS code=2IOS 块不工作,给出错误:EXC_BAD_ACCESS 代码=2
【发布时间】:2014-07-03 03:54:22
【问题描述】:

我在调用块时遇到问题,我不断收到错误 EXC_BAD_ACCESS code=2。

.h file
    @interface TheClass : UIView

    typedef void (^AnotherBlock)();
    @property (copy) AnotherBlock block;

    - (void) testMethod;

    @end

.m file
    #import "TheClass.h"

    @implementation TheClass

    - (id)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];
        if (self) {
            [self testMethod];
        }
       return self;
    }

    - (void) testMethod {
        self.block();
    }


    @end

在主视图控制器中

.m file
    #import "MainViewController.h"
    #import "TheClass.h"

    @interface MainViewController ()

    @property TheClass *mClass;

    @end

    @implementation MainViewController

    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    {
        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
        if (self) {
            // Custom initialization
        }
        return self;
    }

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    }

    - (IBAction)button:(id)sender {
        self.mClass = [[TheClass alloc] init];
        [self.mClass testMethod];

        self.mClass.block = ^ {
            NSLog(@"Remote Block Worked");
        };
    }
    @end

按钮已链接并正常工作,触摸时我收到错误消息。 在调试器中有一条消息说:

    _block AnotherBlock <parent is NULL>

任何帮助都会很棒。谢谢

【问题讨论】:

  • 在调用块指针变量之前,您应该始终测试它不是nil

标签: xcode class objective-c-blocks


【解决方案1】:

在为 block 变量分配任何内容之前,您正在调用 testMethod。在调用 testMethod 之前,请确保其中有内容。

【讨论】:

  • 感谢成功,我将块创建移至 viewDidLoadMethod,并在触摸按钮时调用 testMethod。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-12
  • 2012-05-07
  • 1970-01-01
  • 2011-05-23
相关资源
最近更新 更多