Could you help me with this error.
I’ve tried this code, with ARC and non ARC.
with ARC is OK. but with non ARC.
How could I do. help me please. ^__^;
When I push the button, the error occures.
**
#import <UIKit/UIKit.h>
@interface FirstViewController : UIViewController {
void (^_myOne)(void);
UIView* _viewOne;
}
@property (nonatomic, retain) void (^myOne)(void);
@property (nonatomic, retain) UIView* viewOne;
- (void)useFirstOne:(void(^)(void))blockOne;
@end
#import "FirstViewController.h"
@implementation FirstViewController
@synthesize myOne = _myOne, viewOne = _viewOne;
- (void)useFirstOne:(void (^)(void))blockOne {
blockOne ();
}
- (void)buttonPressed {
[self useFirstOne:self.myOne]; //If I put this line into 'viewDidLoad', has no problem.
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor redColor];
UIButton* buttonA = [UIButton buttonWithType:UIButtonTypeRoundedRect];
buttonA.frame = CGRectMake(0, 0, 100, 44);
buttonA.center = CGPointMake(160, 350);
[buttonA setTitle:@"Button" forState:UIControlStateNormal];
[buttonA addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:buttonA];
_viewOne = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
[self.view addSubview:self.viewOne];
_myOne = ^{
self.viewOne.backgroundColor = [UIColor grayColor];
};
}
@end
**
This:
needs to be this:
This is because block objects are stack allocated, which means that they are deallocated when they go out of scope. So when the
viewDidLoadmethod finishes executing, the block held in_myOnewill be deallocated, and if you try to use it it will crash. When you copy a block, the copy is heap allocated and will survive until it is released.