[英]Object becomes nil after init inside block
這是我的代碼:
__block UIButton buttonOne;
__block UIButton buttonTwo;
- (UIView *)addressOptionView
{
if (!_addressOptionView) {
_addressOptionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), addressButtonArray.count * BasedAdditionForSegment)];
void (^setupButton)(UIButton *, NSString *, NSInteger) = ^
void (UIButton *button, NSString *title, NSInteger idx) {
if (!button)
button = [[UIButton alloc] init];
button.frame = ({
CGRect frame = _addressOptionView.bounds;
frame.origin.x += 20;
frame.size.width -= 40;
frame.origin.y = idx * BasedAdditionForSegment;
frame.size.height = BasedAdditionForSegment;
frame;
});
[button setTitle:title forState:UIControlStateNormal];
};
setupButton(buttonOne, addressButtonArray[0], 0);
setupButton(buttonTwo, addressButtonArray[1], 1);
DebugLog(@"%@", buttonOne);
[_addressOptionView addSubview:buttonOne];
[_addressOptionView addSubview:buttonTwo];
}
return _addressOptionView;
}
buttonOne
和buttonTwo
不是屬性。
在我調用addressOptionView getter
,這兩個按鈕會立即被釋放,因此它們不會顯示在視圖中(我想在NSLog
時為nil)。
我將setupButton
塊更改為@property
,它也不起作用。 將兩個按鈕更改為@property
也不起作用。
但是,當我將setupButton
塊更改為
UIButton * (^setupButton)(NSString *, NSInteger)
確實出現了兩個按鈕,但是以后我無法以其他方法訪問它們(已經為nil
)。
有人可以簡要說明我做錯了什么嗎? 我該如何運作? 謝謝。
@implementation SomeObject {
// do not make these __block types
UIButton* _buttonOne;
UIButton* _buttonTwo;
}
- (UIView *)addressOptionView
{
// most of method removed for brevity, see question
void (^setupButton)(UIButton*__autoreleasing*, NSString *, NSInteger) = ^
void (UIButton*__autoreleasing*button, NSString *title, NSInteger idx) {
NSAssert( button, @"Must not pass nil reference as button" );
UIButton* localButton = *button;
if (!localButton) {
// continue to work on the more convenient localButton, but make sure
// that the button reference is written to the ivar...
localButton = *button = [UIButton buttonWithType:UIButtonTypeCustom];
}
// other button setup clipped
};
// compiler will generate strong stack-allocated temporary variable here
// to deal with autoreleasing assignment, but make sure ivars are not
// __block class
setupButton(&_buttonOne, addressButtonArray[0], 0);
setupButton(&_buttonTwo, addressButtonArray[1], 1);
DebugLog(@"%@", _buttonOne);
[_addressOptionView addSubview:_buttonOne];
[_addressOptionView addSubview:_buttonTwo];
// top-most branch was clipped for this example
return _addressOptionView;
}
這行是問題所在...
button = [[UIButton alloc] init];
完成此操作后,傳遞給塊的按鈕引用的副本現在指向內存中的其他位置。 這不會改變其中原始按鈕引用指向你在那里復制的按鈕引用指向只更改。 請記住,目標-c是價值傳遞!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.