内存泄漏iOS

时间:2013-10-11 02:43:43

标签: ios memory-leaks

我的记忆在这里泄漏了什么:

我有全局变量:

@property (nonatomic, strong) NSArray *productArray;

我有从核心数据查询数据的函数实现:

- (NSArray *)fetchallProductWithTag:(NSString *)tag
{
   NSPredicate *predicate = 
     [NSPredicate predicateWithFormat:@"tags.name contains [cd] %@", tag];

   NSSet *itemsSet = [self.managedObjectContext        
         fetchObjectsForEntityName:TABLE_NAME_PRODUCT 
                     withPredicate:predicate 
                           columns:nil unique:NO];

    return itemsSet.allObjects;
}

以下是类别类中 fetchObjectsForEntityName:withPredicate:columns:的实现:

- (NSSet *)fetchObjectsForEntityName:(NSString *)entityName
                   withPredicate:(NSPredicate *)predicate
                         columns:(NSArray *)columns
                          unique:(BOOL)unique
  {
      NSEntityDescription *entity = [NSEntityDescription
            entityForName:entityName inManagedObjectContext:self];

      NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];

     [request setEntity:entity];
     [request setPredicate:predicate];
     [request setReturnsDistinctResults:unique];

     if( columns.count > 0)
        [request setPropertiesToFetch:columns];

     if( columns.count > 0 || unique )
        [request setResultType:NSDictionaryResultType];

     NSError *error = nil;

     NSArray *results = [self executeFetchRequest:request error:&error];

     if (error != nil)
     {
          [NSException raise:NSGenericException 
               format:@"Error fetching in %@; error:%@", 
               entityName, error.localizedDescription];
     }

    if( results.count > 0 )
    {
        return [NSSet setWithArray:results];
    }
    return nil;
}

在我的视图控制器中,我有这个函数调用:

self.productArray = [myClass fetchAllProductWithTag:@"All"];

然后在viewcontroller类代码中的某处重置productArray的值:

self.productArray = [myClass fetchAllProductWithTag:@"Favorites"];

然后发生泄漏。

1 个答案:

答案 0 :(得分:-2)

事实证明导致泄漏的行是try-catch语句。我有这样的事情:

Product *product = nil;

@try 
{
   product = [self.productArray objectAtIndex:index];
}
@catch (NSException *exception) 
{
   return;        
}

我不想检查索引是否超出范围。所以我将它放在try-catch中并在发生异常时返回。

所以,我试图删除try-catch,并且有类似的东西:

Product *product = nil;

if( index < self.productArray.count )
  product = [self.productArray objectAtIndex:index]
else 
  return;

最后,泄漏消失了。