我在行上获得了一个EXC_BAD_ACCESS / KERN_INVALID_ADDRESS“self handleError:error ..etc”
我认为该块会保留自己? “self”是一个viewController,可能会从堆栈中弹出,但是不应该保留它?
[[PWGamesResource sharedInstance] createRandomGameRequest:requestDict
withFailure:^(NSError *error) {
[self handleError:error withTryAgain:^{
[self sendNewRandomGameRequest:difficulty];
}];
}];
答案 0 :(得分:2)
如果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被块捕获。
答案 1 :(得分:-2)
你应该避免在可能的情况下使用自己。
试试这个:
__weak __typeof(self)weakSelf = self;
[[PWGamesResource sharedInstance] createRandomGameRequest:requestDict
withFailure:^(NSError *error) {
[weakSelf handleError:error withTryAgain:^{
[weakSelf sendNewRandomGameRequest:difficulty];
}];
}];