2010-08-13 21 views
0

我使用CoreData來存儲數據,並且我有一些實體。 我如何通過CoreData做一些自定義語句? 所以我的意思是我不想獲取數據表中的所有記錄,但例如「keyValue = something的每個元素」,沒有更多。或者例如最後3個元素。等等等等。 那麼我可以通過什麼方式自定義語句來獲取所需的數據?CoreData自定義提取(並非所有數據)iPhone

回答

1
// Init your fetchRequest 
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 

NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"entityName" inManagedObjectContext:yourManagedObjectContext]; 

// create the relation between request and the created entity 
[fetchRequest setEntity:entityDescription]; 

// Set your predicate for this request 
NSPredicate *somePredicate = [NSPredicate [email protected]"%K == %@", @"name", @"John"]; 
[fetchRequest setPredicate:somePredicate]; 

// Pushing the results into a array 
NSError *error = nil; 
NSArray *fetchResults = [yourManagedObjectContext executeFetchRequest:fetchRequest error:&error]; 

[fetchRequest release]; 

此示例取從實體 「entityName」 的所有記錄,其中 「name」 屬性等於 「John