阻止非ARC,内存泄漏问题

时间:2012-02-29 07:37:31

标签: objective-c ios memory-leaks automatic-ref-counting objective-c-blocks

你能帮我解决这个错误。 我用ARC和非ARC试过这段代码。 用ARC就可以了。但非ARC。 我该怎么办?请帮帮我。 ^ __ ^;

当我按下按钮时,会发生错误。 **

#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

**

1 个答案:

答案 0 :(得分:5)

此:

_myOne = ^{
    self.viewOne.backgroundColor = [UIColor grayColor];
};

需要这样:

_myOne = Block_copy(^{
    self.viewOne.backgroundColor = [UIColor grayColor];
});

这是因为块对象是堆栈分配,这意味着它们在超出范围时会被释放。因此,当viewDidLoad方法完成执行时,_myOne中保存的块将被释放,如果您尝试使用它,它将崩溃。复制块时,副本堆分配并将一直存在直到它被释放。