2013-05-08 50 views
0

我是xcode和核心數據的新手。我想要使​​用核心數據執行以下查詢。如何使用NSpredicate查詢

從roomtable選擇房間數(roomtype),其中roomtype = @「ac single」,roomstatus = @「YES」;

請指導我如何使用NSPredicate來執行我的查詢。

回答

1

步驟,處理核心數據有:

創建一個提取請求拉對象到託管對象上下文

// Assuming you have an entity called Rooms: 
[NSFetchRequest fetchRequestWithEntityName:@"Rooms"]; 

現在創建謂詞被應用到實體篩選返回什麼

// Assuming that the Rooms entity has attributes for "roomType" and "roomStatus" 
// I'd actually use %K and attributes - but this will do until you learn about them. 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"roomType == %@ and roomStatus == %@", @"ac single", @"YES"]; 

[request setPredicate:predicate]; 

RUN該找取請求

// Assuming you have the managed Object Context in a property 
NSError *error; 
NSArray *results = [self.moc executeFetchRequest:request error:&error]; 

// Make sure the results are not nil, if they are handle the error 
if (!results) { 
    // Handle error in here using the error parameter you passed in by reference. 
} 

現在的結果是一個數組,你可以得到滿足謂詞只需用實體的數量:

NSUInteger resultCount = [results count]; 

這是所有標準的東西與核心數據時。如果您按照自己的方式工作並嘗試理解這些步驟,那麼編寫自己的提取請求將會很長。

+0

謝謝Abizern。有效!!! – 2013-05-13 09:19:18