【发布时间】: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