3

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

如果调用此方法的对象被释放,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];
        }
4

1 回答 1

0

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

于 2014-02-19T04:24:30.683 回答