Reputation:
I am calling the block from second class which has been declared and maintained in first class.
In ViewController.h
@property (copy) void (^simpleBlock)(NSString*);
In View Controller.m
- (void)viewDidLoad {
[super viewDidLoad];
self.simpleBlock = ^(NSString *str)
{
NSLog(@"Hello My Name is: %@",str);
};
}
In SecondViewController.m
In ViewDidload
ViewController *VC = [[ViewController alloc]init];
VC.simpleBlock(@"Harjot");//bad execution error
Please suggest me some solutions because the code is giving me bad execution error. How can i call the block in any another way?
Upvotes: 0
Views: 265
Reputation: 2547
It's the correct way of run the block. However if you try to run a block that is nil
you'll have a crash - so you should always check that it's not nil
before calling it:
ViewController *vc = [[ViewController alloc] init];
if (vc.simpleClock) {
vc.simpleBlock(@"Harjot");//this will not get called
}
The reason why in your case the block is nil
is because you set it in viewDidLoad
- however viewDidLoad
is not called until its view is ready to go on screen. For testing purposes try to move the assignment from viewDidLoad
to init
and this should work:
- (instancetype)init
{
self [super init];
if (self) {
_simpleBlock = ^(NSString *str)
{
NSLog(@"Hello My Name is: %@",str);
};
}
return self;
}
Upvotes: 1