2013-10-11 95 views
2

什麼cuases我的內存泄漏的位置:內存泄漏的iOS

我有全局變量:

@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:列: from category category:

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

然後在視圖控制器類代碼的地方我重置productArray的價值:

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

然後發生泄漏。

+0

ARC還是ARC? –

+0

你怎麼知道有泄漏? –

+0

使用ARC的Im。 xcode 5 – Hokage

回答

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

最後,泄漏不見了。

+0

什麼在try-catch,爲什麼會導致泄漏? – Hokage