2012-12-12 39 views
0
+ (NSArray *) fetchAllContactsInContext:(NSManagedObjectContext *)a_context 
{ 
    NSFetchRequest *_request = [[NSFetchRequest alloc] init]; 
    [_request setEntity:[NSEntityDescription entityForName:@"Contact" inManagedObjectContext:a_context]]; 

    NSSortDescriptor *_sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastName" ascending:YES]; 
    NSArray *_sortDescriptors = [[NSArray alloc] initWithObjects:_sortDescriptor, nil]; 
    [_request setSortDescriptors:_sortDescriptors]; 

    NSError *_fetchError=nil; 
    NSArray *_results = [[NSArray alloc] initWithArray:[a_context executeFetchRequest:_request error:&_fetchError]]; 
    [_sortDescriptor release]; 
    [_sortDescriptors release]; 
    [_request release]; 

    if (_fetchError){ 
     NSLog(@"Contact - Error fetching contacts %@", [_fetchError localizedDescription]); 
    } 
    [_fetchError release]; 
    return [_results autorelease]; 
} 

我想問一下,這個函數是否泄漏內存?其實樂器是說這個功能泄漏了很多內存。這個函數是否產生任何內存泄漏?

你能幫我解決內存問題嗎?

+0

注:不考'_error',以確定是否有錯誤,測試'_results',有如果沒有錯誤,就不能保證值。另外,這些天領先的下劃線「_」通常只用於iVars,這有助於他人閱讀您的代碼。當然,所有這些都是名詞問題。 – zaph

+0

我不認爲你需要釋放'_fetchError'。否則,可能會導致返回的值泄漏。嘗試運行產品 - >分析以查看是否有警告......或切換到ARC。 :-) –

回答

1

如果你需要看到保留,發佈和自動釋放出現一個對象使用儀器:在儀器

運行,在設定「記錄的引用計數」關於分配(你必須停止記錄設置的選項)。導致問題代碼運行,停止錄製,在那裏搜索感興趣的ivar,深入瞭解,您將能夠看到所有保留,發佈和autoreleases發生。

enter image description here

這裏是爲iOS 4.3簡化了使用ARC及以上版本:

+ (NSArray *) fetchAllContactsInContext:(NSManagedObjectContext *)aContext { 
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Contact"]; 

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastName" ascending:YES]; 
    [request setSortDescriptors:@[sortDescriptor]]; 

    NSError *fetchError; 
    NSArray *results = [aContext executeFetchRequest:request error:&fetchError]; 

    if (results == nil){ 
     NSLog(@"Contact - Error fetching contacts %@", [fetchError localizedDescription]); 
    } 
    return results; 
} 
+0

我是否需要將我的項目設置更改爲使用ARC?或重構此文件將工作?目前我的項目是NON-ARC項目。 –

+0

無論你使用ARC還是個人喜好,我都選擇在我的項目中使用ARC。 YOu可能會尋找另一個SO如何轉換爲ARC的答案。 – zaph

0

爲什麼[_fetchError release];在那裏?

爲什麼不使用ARC?

嘗試將此代碼重構爲AR​​C。

+0

我是否需要將我的項目設置更改爲使用ARC?或重構此文件將工作?目前我的項目是NON-ARC項目。 –

+0

重構它,它會自動轉換爲ARC。在arc版本中,保留,複製,自動釋放並由編譯器本身實現。所以沒有泄漏和殭屍的機會。 –

+0

我是否需要將我的項目設置更改爲使用ARC? –