[英]Asynchronous block call to self crashes with EXC_BAD_ACCESS in Swift
[英]EXC_BAD_ACCESS on self in block
我在“ self handleError:error ..etc”行上得到一個EXC_BAD_ACCESS / KERN_INVALID_ADDRESS
我以為塊會保留自我? “ self”是一個可能從堆棧中彈出的viewController,但是不應該保留它嗎?
[[PWGamesResource sharedInstance] createRandomGameRequest:requestDict
withFailure:^(NSError *error) {
[self handleError:error withTryAgain:^{
[self sendNewRandomGameRequest:difficulty];
}];
}];
如果將self
釋放確實是您的真正問題,那么完整的解決方案是在塊內強烈引用self的弱引用,這樣您就可以避免在塊內執行時將其釋放的風險:
強烈引用塊內的弱指針。
__weak MyObject *weakSelf = self; // a weak reference of self so you can avoid any retain cycles
myBlock = ^{
MyObject *innerSelf = weakSelf; // a block-local strong reference so that you can avoid to have weakSelf deallocated while executing
NSLog(@"MyObject: %@", innerSelf);
};
避免直接使用變量,因為這會導致保留周期。 如果直接在塊內使用實例變量,則該塊將捕獲self,因此您必須使用其訪問器來引用實例變量。
__weak MyObject *weakSelf = self;
myBlock = ^{
MyObject *innerSelf = weakSelf; // a block-local strong reference
NSLog(@"MyObject: %@", innerSelf);
NSLog(@"MyObject ID: %d", innerSelf.objectID);// accessing the property through the block's strong reference to self
};
如果您像這樣直接使用實例變量:
NSLog(@"MyObject ID: %d", _objectID);
編譯器將_objectID
解釋為self->_objectID
,其中self被您的塊捕獲。
您應盡可能避免在塊中使用self。
嘗試這個:
__weak __typeof(self)weakSelf = self;
[[PWGamesResource sharedInstance] createRandomGameRequest:requestDict
withFailure:^(NSError *error) {
[weakSelf handleError:error withTryAgain:^{
[weakSelf sendNewRandomGameRequest:difficulty];
}];
}];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.