在autoreleasepool {}中释放外部创建的自动释放对象

时间:2013-05-07 22:28:03

标签: objective-c autorelease nsautoreleasepool nsjsonserialization

如何强制autoreleasepool释放我在autoreleasepool {}之外创建的自动释放对象

使用

的代码
- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection {

    NSError *error = nil;
    id response = [NSJSONSerialization JSONObjectWithData:responseData options:nil error:&error];
    [responseData release];
    if (error) {
            NSLog(@"ERROR JSON PARSING : %@", error.localizedDescription);
    }

    [delegate databaseUpdates:response connection:self];
}

- (void)databaseUpdates:(id)_updates connection:(URLConnection *)_urlConnection {
    if (_updates) {

        NSDictionary *updates = nil;
        @autoreleasepool {

            updates = [[_updates valueForKey:@"objects"] retain];

            //Release _updates here!?!
        }
    }
}

非常感谢

2 个答案:

答案 0 :(得分:3)

只需在自动释放池的范围内调用autorelease,即可自动将对象添加到池中。虽然,看起来你正试图在这里解决错误的问题。如果你的意思是_updates,那么这不应该是方法的内存管理,而是调用者(它已经是!JSONObjectWithData:options:error:已经返回一个自动释放的实例),如果你的意思是{{1好吧,根本就不要保留它。

答案 1 :(得分:0)

这是不可能的。我想你需要这个

- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection {
    @autoreleasepool {
        NSError *error = nil;
        id response = [NSJSONSerialization JSONObjectWithData:responseData options:nil error:&error];
        [responseData release];
        if (error) {
                NSLog(@"ERROR JSON PARSING : %@", error.localizedDescription);
        }

        [delegate databaseUpdates:response connection:self];
    } // response will be released here
}