2

是什么导致我的内存泄漏:

我有全局变量:

@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"];

然后发生泄漏。

4

1 回答 1

-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;

最后,泄漏消失了。

于 2013-10-18T04:10:55.940 回答