0

你能幫我解決這個錯誤。 我試過這個代碼,用ARC和非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 

**

回答

5

此:

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

需要是這樣的:

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

這是因爲塊對象分配堆疊,這意味着當它們超出範圍時,它們將被釋放。所以當viewDidLoad方法完成執行時,_myOne中的塊將被釋放,如果你嘗試使用它,它會崩潰。當您複製一個塊時,副本是堆分配,並將繼續,直到它被釋放。

+0

哦。謝謝。非常。 ^^。謝謝。謝謝。 – user1239633 2012-02-29 08:01:17