2013-06-12 64 views
0

我使用NSFetchedResultsController重寫我的項目。它幾乎工作。但是我想要做的事情是在前置代碼中很容易,但我不知道在哪裏編碼。如何查看NSFetchedResultsController是否不返回任何內容?

當我的UITableView的dataSource爲空時,我想添加一個消息「在TableView中添加一個對象,按下+按鈕」的子視圖。

如果沒有任何內容需要顯示,或者用戶刪除了TableView的所有對象,則此子視圖應在啓動時顯示。

是最好的地方是numberOfRowsInSection(我只有一節),以出頭像

id <NSFetchedResultSectionInfo> sectionInfo = [[[self fetchedResultsController] sections] objectAtIndex:section]; 

if ([sectionInfo numberOfObjects] == 0) 
{ 
AddSubview 
} else { 
remove subview if needed 
} 
... 

感謝您的幫助。

最好的問候,
雅克

+0

這應該工作,你試過嗎? –

+0

我的回答能幫助你嗎? – pmk

+0

Martin R.事實上,我編碼它,但不編譯和測試它,我需要回家,我沒有在工作的Mac ;-)我會盡快給你一個更新。 –

回答

0

比方說,你有一個CoreData實體,稱爲Countries。這個國家有屬性countryName。要檢查是否存在Countries類型的實體,我叫下面的方法:

- (BOOL)countryExistsWithName:(NSString *)countryName{ 

    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Countries"]; 

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"countryName == %@, countryName]; 
    [fetchRequest setPredicate:predicate]; 

    NSError *error; 
    NSUInteger count = [self.managedObjectContext countForFetchRequest:fetchRequest error:&error]; 

    if (count == NSNotFound) { 
     // error 
     NSLog(@"error"); 
     return NO; 
    } 
    if (count > 0) { 
     // at least one country found 
     return YES; 
    } 

    return NO; 
} 

編輯: 如果你不想問一定countryName,你根本就檢查所有Countries,執行取回之後:

- (NSInteger)countAllCountries{ 

    // We use an NSPredicate combined with the fetchedResultsController to perform the search 
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Countries"]; 

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"countryName" ascending:YES]; 
    fetchRequest.sortDescriptors  = @[sortDescriptor]; 

      NSError *error; 
    NSUInteger count = [self.managedObjectContext countForFetchRequest:fetchRequest error:&error]; 

    if (count == NSNotFound) { 
     // error 
     NSLog(@"error"); 
     return 0; 
    } 
    if (count > 0) { 
     // at least one country found 
     return count; 
    } 

    return count; 

} 

使用此方法,您應該很容易確定您的數據源是否是emty。 希望它有幫助

+0

你的答案將與舊的行爲一起工作。 使用NSFetchedResultsController,數據源直接連接到moc。 使用與NSFetchedResultsController請求相同的請求創建方法效率不高。 更有效的方式似乎使用NSFectedResultsController –

相關問題