2012-06-06 26 views
0

我有一個名爲Item的核心數據實體,它有一個日期字段。我想找回我的數據庫中的所有項目按日期分組,例如:核心數據:檢索按日期分組的所有項目實體?

Item one, date: 1/1/11 
Item two, date: 1/1/11 
Item three, date: 1/2/11 

應該返回:

(Item one, Item two), (Item three) 

有人能告訴我什麼是做到這一點的最好方法是什麼?謝謝!

+0

順便說一句,如果對問題有所幫助,將答案標記爲正確,這被認爲是一個好主意。如果我的答案不夠好,請告訴我,我可以更新它。 – RonLugge

回答

0

您可以做的最好的方法是訂購它們,然後根據相同的日期創建分組。 (注:雖然我使用真正的函數名作爲適當,這僅僅是僞代碼填補空白自己,或者如果你需要更多的幫助問)

NSFetchRequest *request=[NSFetchRequest alloc init]; 
NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey: @"foo" ascending:YES]; 
[request setSortDescriptors:[NSArray arrayWithObject:sort]]; 
//Fetch 

NSMutableArray* master=[NSMutableArray array]; 
NSMutableArray* current=[NSMutableArray array]; 
NSDate *lastDate=[fetchedObjectsArray objectAtIndex:0].date; 
forin(ManagedObjectSubclass *foo in fetchedObjectsArray) 
{ 
//You'll need to figure out an algorithm to determine if two dates are the same. 
//This code WILL NOT work as written. 
    if(foo.date == lastDate) 
    { 
     [current addObject:foo]; 
    } 
    else 
    { 
     [master addObject:current]; 
     current=[NSMutableArrayArrwayWithObject foo]; 
    } 
} 
[master addObject:current]; 

這應該是足夠多的讓你開始了。