NSJSONSerialization在回调块中泄漏

时间:2012-01-08 00:38:51

标签: objective-c memory-management nsurlconnection objective-c-blocks nsjsonserialization

我正在尝试通过以下方法使用Blocks作为API请求的回调。此方法采用嵌套在此方法的Block中的Block。它有效...但是,

如果已释放调用此方法的Object,则NSJSONSerialization会转储大量内存泄漏。一切都在运行,这一切都很好。泄漏仅在请求对象消失后发生。泄漏几乎都是NSPlaceHolder类型。

我在我的智慧结束,任何想法都非常感谢!

    - (void)sendRequestUsingNSURLConnectionWith:(NSURLRequest *)request andCallback:(void (^)(id))handler
        {
            __block __typeof__(self)blockSelf = self;

            // CL: build a block to be run asynchronously
            ApiClientCallback handleResponse = [[^(NSURLResponse *response, NSData *data, NSError *error) {

                id results = nil;

                // CL: http errors would be caught here.
                if (error) {
                    NSLog(@"[%@ %@] HTTP error: %@", NSStringFromClass([blockSelf class]), NSStringFromSelector(_cmd), error.localizedDescription);
                    results = error;
                }
                else {
                // CL: parse the JSON
                    NSError *jsonError = nil;
                    NSError *apiError = nil;
                    if (data) {
                        results = [NSJSONSerialization JSONObjectWithData:data 
                                                                  options:NSJSONReadingMutableContainers 
                                                                    error:&jsonError];
                    }
                    else {
                        results = nil;
                    }
                    // CL: json errors would be caught here.
                    if (jsonError) {
                        NSLog(@"[%@ %@] JSON error: %@", NSStringFromClass([blockSelf class]), NSStringFromSelector(_cmd), error.localizedDescription);
                        results = error;
                    }
                    // CL: Check for API errors.
                    else if ([blockSelf checkApiErrorCode:results error:&apiError]) {
                        //CL: if there's an error make the NSError object the result.
                        if (apiError) results = apiError;
                    }
                }
                // CL: Send result to the completion block of the requesting object
                handler(results);

            } copy] autorelease];

            [NSURLConnection sendAsynchronousRequest:request 
                                               queue:self.opQueue 
                                   completionHandler:handleResponse];
        }

1 个答案:

答案 0 :(得分:0)

根据要求我在这里记录结论。事实证明,我忘了在子类的dealloc方法中调用super dealloc。这导致super在重新分配时泄漏所有保留的属性。程序员错误。请注意,这种情况发生在ARC之前。