2012-08-08 92 views
0

我需要獲取值爲xxx的特定託管實體。如何使用NSFetchRequest獲取特定值

我的管理對象是

Subscriptions : NSManagedObject{ 
    @property (nonatomic, retain) NSString * name; 
    @property (nonatomic, retain) NSNumber * id; 
    @property (nonatomic, retain) NSNumber * category; 
    @property (nonatomic, retain) NSNumber * frequency; 
    @property (nonatomic, retain) NSNumber * alertType; 
} 

我需要獲取只有一個實體,其中名爲「XXX」。 (只有一個實體,其中名稱是xxx) 我還需要獲取所有實體的類別爲1.

我該如何使用NSFetchRequest執行此操作。我知道如何使用NSFetchedResultsController獲取實體的所有實體值,但我只想獲取名稱爲xxx的一個實體值。

回答

0

假設你有一個NSManagedObjectContext *context,則:

NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease]; //Note don't use autorelease if you're using ARC 
request.entity = [NSEntityDescription entityForName:@"Subscriptions" inManagedObjectContext:context]; 
NSString *someName = @"xxx"; 
request.predicate = [NSPredicate predicateWithFormat:@"name ==[c] %@", someName]; //[c] means case insensitive 
NSArray *result = [context executeFetchRequest:request error:nil]; 

結果數組將包含所有返回的結果,將是Subscriptions類型。如果謂詞僅匹配一個項目,則只有一個結果,如果匹配無,則該陣列將被初始化,但其count屬性將爲0.您可以查看NSPredicate Class Reference以及如何將它與CoreData一起使用。

+0

非常感謝您的寶貴意見。 – Anand 2012-08-09 10:50:32