【问题标题】:I cant find this memory leak. I thought I was releasing everything properly我找不到这个内存泄漏。我以为我正在正确释放一切
【发布时间】:2011-06-28 02:26:09
【问题描述】:

我找不到这个内存泄漏。我以为我一直在适当地释放东西。这是有问题的代码块。

 - (void) createProvince:(NSString *) provinceName {

    // if province does not exist create it
    if ([self hasProvince: provinceName] == NO) {

        // get the province object
        NSPredicate *predicate;
        predicate = [NSPredicate predicateWithFormat:@"Name == %@", provinceName];

        NSMutableArray *provArray = [[NSMutableArray alloc] init];
        [provArray setArray: [CoreDataHelper searchObjectsInContext:@"Province" :predicate :@"Name" :YES :[self managedObjectContext]]];

        NSIndexPath *indexPath;
        indexPath = [NSIndexPath indexPathForRow:0 inSection: 0];

        [[self provinces] addObject: [provArray objectAtIndex: [indexPath row]]];
        [provArray release];

        // create a cities array to hold its selected cities
        NSMutableArray *array = [[NSMutableArray alloc] init];
        [[self cities] addObject: array];
        [array release];
    }
}

漏洞在这里:

[[self provinces] addObject: [provArray objectAtIndex: [indexPath row]]];

NSMutableArray *array = [[NSMutableArray alloc] init];
[[self cities] addObject: array];

我正在创建局部变量,通过适当的设置器将它们分配给我的实例变量,然后释放局部变量。我不确定发生了什么。

【问题讨论】:

    标签: objective-c debugging ios memory-leaks


    【解决方案1】:

    您是否有一个 dealloc 方法可以正确释放所有内容?

    请注意,泄漏是向您显示分配了某些内容的位置。它不会向您显示实际泄漏的位置;保留没有明确平衡。

    【讨论】:

      【解决方案2】:

      让我们看看这个:

      NSMutableArray *array = [[NSMutableArray alloc] init];
      [[self cities] addObject: array];
      [array release];
      

      当你alloc一个对象时,它的保留计数设置为1:

      NSMutableArray *array = [[NSMutableArray alloc] init]; # retain count of array is 1
      

      当您将对象添加到 NSMutableArray 时,该对象的 retain 计数会增加:

      [[self cities] addObject: array]; # retain count of array is 2
      

      当你releasearray 时,它的保留计数会减少:

      [array release]; # retain count is now 1
      

      一旦你的方法结束,你仍然拥有可变数组[self cities]拥有的数组。

      因为[self cities] 似乎没有被释放或清空,所以这就是泄漏的地方。

      您需要在某个时候清空或释放可变数组,释放其中包含的对象。如果cities 是类属性,则可能是release 在类释放时。

      编辑

      修复了init-alloc 错误。

      【讨论】:

      • 好吧,这是有道理的。我有一个 dealloc 应该被调用来释放城市,但它不是。我认为,这告诉我有未释放的对象需要先释放。
      • init 不会改变对象的保留计数; alloc 分配的保留计数为 +1。绝对保留计数是没有用的。
      猜你喜欢
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-20
      相关资源
      最近更新 更多