objective-c - block 和内存管理

标签 objective-c ios cocoa-touch

昨天我问了一个关于内存管理和单例的问题(Proper Management Of A Singleton Data Store In IOS With Web Service)。在过去的 36 小时里,我一直在绞尽脑汁试图找出这个问题,在使用 NSLog 等进行了大量测试之后,我只能得出结论, block 内分配的对象没有被自动释放。我使用 block 作为处理异步网络服务响应的方式。我还从需要发出 Web 服务请求的 View Controller 发送一个 block ,以便它可以根据 Web 服务的响应执行任何操作。希望对我的代码的全面概述有助于获得解决方案,我将产生问题的所有代码放在这里:

第一步是从我的 Root View Controller 发出请求。当它加载时,我请求所有用户的“Hollers”一个我在内部使用的术语,本质上是指事件。当加载 Root View Controller 时,我调用一个包含以下代码的方法:

HollerWebService *api = [[HollerWebService alloc]init];
//NSLog(@"About to get the hollers for userId: %@", [[[CurrentSession defaultStore]currentUser]userId]);
[api getLatestHollers:[[[CurrentSession defaultStore]currentUser]userId] completionBlock:^(BOOL succeeded) {
    //If the user has 0 hollers, display one of the illustrations
    [self.tableView reloadData];
    [self stopLoading];
    if( !succeeded ){
        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Could not connect to Holler" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [av show];
        [av release];
    }
    else
    {
        for( Holler *hN in [[HollerStore defaultStore] allHollers] )
        {
            //Retain count of all the hollers is 
            NSLog(@"Retain count of the holler is %i", [hN retainCount]);
        }
    }
}];

[api release];

如您所见,我有一个注释区域,它将保留计数打印到 NSLog,这是我调试过程的一部分。此时,它告诉我每个对象的保留计数为 2,这意味着下一组代码中生成的原始 Holler 尚未自动释放。下一组代码在我的实际 Web 服务中。我已经围绕此方法的关键部分添加了评论,这导致保留计数增加:

- (void)getLatestHollers: (NSString *)userId completionBlock:(void (^)(BOOL succeeded))handler
{
    [self getRequest:[[NSString alloc]initWithFormat:@"hollers/feed?user_id=%@",userId] completionBlock:^(NSData *receivedData, NSURLResponse *receivedResponse, NSError *error) {
    if( error == nil )
    {
        SBJsonParser *json = [SBJsonParser new];
        NSArray *response = [json objectWithData:receivedData];
        [json release];
        //NSLog(@"Got the latest Hollers. %@", response);
        HollerStore *hStore = [HollerStore defaultStore];
        for( NSDictionary *holler in response )
        {
            //At this point Holler *h is being sent an autoreleased holler
            //from the parseHoller: method.  At this point it's retain count is 1
            Holler *h = [self parseHoller:holler];
            [hStore addHoller:h];
            //Now that I've added it to my singleton the retain count is 2, although I'm 
            //assuming the autorelease pool will eventually come through and reduce this 
            //to 1 but it never happens
        }
        handler(YES);
    }
    else
    {
        NSLog(@"The API failed :(, %@", [error localizedDescription]);
        //Let the requestor know that this request failed
        handler(NO);
    }
    }];
}

此时保留计数保持为 2,而不是 1,因此当我从我的单例中删除该对象时,会导致内存泄漏。我唯一可以得出的结论是,我遇到了某种与 block 相关的内存问题。如果有人可以提供一些见解,将不胜感激!!!

最佳答案

您根本不应该使用 retainCount永远 - Apple 真的应该将它从 SDK 中删除,因为它根本没有用。出于技术原因查看此问题,了解为什么您不应该直接使用它:

When to use -retainCount?

我将跳到有人发帖说您应该使用它并指出这一点的原始问题。您很可能有内存泄漏,但保留计数不是解决它的正确方法!

关于objective-c - block 和内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7028664/

相关文章:

objective-c - 更改主窗口上的 Alpha - Cocoa

c# - 无法将 Microsoft.ProjectOxford.Face NuGet 安装到 Xamarin Studio iOS 项目中

objective-c - UIDocument openWithCompletionHandler 成功返回 NO

objective-c - NSMutableData 的 mutableBytes 和 bytes 方法之间的区别

ios - 从 block 中返回一个值

iphone - 同一动画 block 中的两个属性更改具有不同的持续时间。为什么?

objective-c - AFNetworking:带有 application/x-www-form-urlencoded 的 POST 请求

objective-c - 如何打印出方法名称和行号并有条件地禁用 NSLog?

ios - 为什么我的嵌套 UITableView 不能正常弹跳?

ios - 如何缓存属于自定义 UITableViewCell 的 CollectionViewCell 图像