我使用块来在服务类中执行访问检查,但它正在泄漏内存。有人能指出我的方法有什么问题吗?问题可能与我在块中使用的变量有关。我正在访问实例变量,方法变量和引用超级。
-(RequestDO*)requestWithURL:(NSString*)url andDelegate:(id<RequestDelegate>)delegate_ signURL:(BOOL)sign_ request:(RequestDO*)request_ postData:(NSString*) postData_ {
if([self requiresUpdatedAccess]){
if(accessRequest == nil){
accessRequest = [[UpdatedAccessManager getPaymentStatus:self] retain];
if(accessRequest.processStatus == kRequestComplete){ // Access check is complete (cached)
[accessRequest release], accessRequest = nil;
return [super requestWithURL:url andDelegate: delegate_ signURL:sign_ request:request_ postData: postData_]; // Do original service request
}
else{
Block_release(completionBlock_);
// When access check is done, we will perform this block to process the original request
completionBlock_ = Block_copy(^(){
/*
url - an instance variable
delegate_, sign_, request_ and postData_ is method scoped variables
*/
NSString *updatedUrl = [Service updateUrlWithUserData: url];
[super requestWithURL:updatedUrl andDelegate: delegate_ signURL:sign_ request:request_ postData: postData_];
});
Block_release(failureBlock_);
// If access check fails, we will perform this block to inform about the error
failureBlock_ = Block_copy(^(RequestDO* req_, NSError* err_){
[delegate_ requestFailed:self.request withError: err_];
});
}
}
}
else{
return [super requestWithURL:url andDelegate: delegate_ signURL:sign_ request:request_ postData: postData_]; // This service does not need access check
}
return accessRequest;
}
在dealloc中,我有两个块的Block_release。
答案 0 :(得分:1)
该块将保留所有使用过的变量。在您的情况下,由于在块中使用了对象,因此对象的保留计数将为2。因此,不会调用dealloc并且您有一个经典的保留周期。要解决此声明
__block id blockSelf = self;
在块之前并在块中使用blockSelf而不是self。