2012-07-03 76 views
8

我有一個示例程序,它使用Core Data並在其中加載一個sqlite數據庫。我顯示所有使用此代碼的值如何選擇核心數據中的特定數據?

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Name" 
              inManagedObjectContext:context]; 
[fetchRequest setEntity:entity]; 
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; 

for (Name *name in fetchedObjects) { 
    NSLog(@"ID: %@", name.nameId); 
    NSLog(@"First Name: %@", name.first); 
    NSLog(@"Middle Name: %@", name.middle); 
    NSLog(@"Last Name: %@", name.last); 
} 

此代碼工作正常,我的問題在於我無法選擇特定的數據/記錄。示例我想選擇ID = 1的記錄。

謝謝!

+0

請檢查沿着正確的答案;) – Pierre

回答

16

您必須在執行請求之前使用謂詞(使用NSPredicate)。

類似的東西:

NSPredicate *predicateID = [NSPredicate predicateWithFormat:@"nameID == %d",-1]; 
[fetchRequest setPredicate:predicateID]; 
+0

謝謝!它適用於我:) – kimbebot

10
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Name" 
              inManagedObjectContext:context]; 
[fetchRequest setEntity:entity]; 

//Add following method to your code. this will help you to get desired result. 
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"yourColumnID == %@", yourID]]; 

NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; 

for (Name *name in fetchedObjects) { 
    NSLog(@"ID: %@", name.nameId); 
    NSLog(@"First Name: %@", name.first); 
    NSLog(@"Middle Name: %@", name.middle); 
    NSLog(@"Last Name: %@", name.last); 
} 
+0

感謝您的! :) – kimbebot

+0

歡迎。如果它幫助你可以upvote:D –

相關問題