iPhone EXC_BAD_ACCESS使用块时 [英] iPhone EXC_BAD_ACCESS when using blocks

查看:133
本文介绍了iPhone EXC_BAD_ACCESS使用块时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用块创建一个简单的回调。
我有一个MainViewController addSubView另一个DatePickerViewController.view我创建了一个块像这样

Im trying to create a simple callback using blocks. I have a MainViewController which addSubView another DatePickerViewController.view i created a block like this

typedef void(^DateChangedBlock)(NSDate*);

我有一个方法在我的DatePickerViewController调用

And i have a method on my DatePickerViewController called

setOnDateChangedCallback:(DateChangedBlock)callback

回调在DatePickerViewController的属性中。 DatePickerViewController的视图是一个UIDatePicker实例,将一个IBAction的值绑定到一个改变为执行此操作的方法的值。

I store the callback in a property of the DatePickerViewController. The DatePickerViewController's view is a UIDatePicker instance, ive bound an IBAction to the value changed to a method that does this.

- (IBAction)dateChanged:(id)sender {

    if (dateChangedCallback != nil)
    {
        dateChangedCallback(nil);
    }
}



这里是如何注册在MainViewController

Here is how i register the block in the MainViewController

DatePickerViewController *dateController = [[DatePickerViewController alloc] initWithNibName:@"DatePickerView" bundle:nil];

self.datePicker = dateController;
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 100, 200)];
[self.view addSubview:textView];
DateChangedBlock myBlock = ^(NSDate *newDate) {
 textView.text = @"testing";
};

[self.datePicker setOnDateChanged: myBlock];
[self.datePicker dateChanged:self]; // force trigger (this works).

当我强制触发DatePickerViewController上的dateChanged方法时,它没有问题。但是当日期器本身触发方法通过IBAction我得到一个EXC_BAD_ACCESS错误。此方法在int retVal行中发生错误。

When i force trigger the dateChanged method on the DatePickerViewController it works no problem. But when the datepicker itself triggers the method thru the IBAction i get a EXC_BAD_ACCESS error. The error occurs in this method on the "int retVal" line.

#import <UIKit/UIKit.h>

int main(int argc, char *argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, nil, nil); // THREAD 1: program received EXC_BAD_ACCCESS.**
    [pool release];
    return retVal;
}

我做错了什么?

推荐答案

你应该复制你的块传递给其他方法(如在你的情况下的属性setter)。所以当设置回调块时,这样做:

You should copy your block when passing it to other method (such as attribute setter in your situation). So when setting the callback block do this:

[self.datePicker setOnDateChanged:[[myBlock copy] autorelease]];

创建块时,使用的EXC_BAD_ACCESS原因块变量不会被块本身保留。所以当调用块 - 变量不再存在。

You get the EXC_BAD_ACCESS cause block's variables used when creating the block don't get retained by the block itself. So when calling the block - variables do not exist anymore.

这篇关于iPhone EXC_BAD_ACCESS使用块时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆