2010-11-23 43 views
2

我儘量讓一種具有核心數據「SQL獨特的」請求, 所以我建立了我的NSFetchrequest這樣如何使用NSDictionary從NSArray中填充數據?

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
[fetchRequest setEntity:[NSEntityDescription entityForName:@"my_table" inManagedObjectContext:managedObjectContext]]; 

[fetchRequest setResultType:NSDictionaryResultType]; 
[fetchRequest setReturnsDistinctResults:YES]; 
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:@"first_property",@"second_property",nil]]; 

// Execute the fetch 
NSError *error; 
table_dom = [[NSArray alloc] init]; 
table_dom = [managedObjectContext executeFetchRequest:fetchRequest error:&error]; 
[fetchRequest release]; 

這個看起來不錯的我,但我想我檢索一個NSArray填充的NSDictionary,這是否恰當?

所以我的問題是我如何從table_dom中爲tableview提取數據,我嘗試了很多東西,但沒有人工作?

它必須是: cell.textLabel.text = // 「第一個屬性」 和 cell.detailTextLabel.text = // 「second_property」

也許使它簡單,我可以檢索對象與setReturnsDistinctResults而不是NSDictionary?

感謝

回答

1

你是正確的,你會得到充滿NSDictionary一個NSArray。首先我想指出你的代碼中有內存泄漏。 table_dom = [[NSArray alloc] init];沒有必要,因爲executeFetchRequest:error:將返回NSArray。所以,只需刪除該行。

之後,你有你的數組,你可以做這樣的事情:

NSDictionary *dict = [table_dom objectAtIndex:indexPath.row]; 
cell.textLabel.text = [dict objectForKey:@"first_property"]; 
cell.detailTextLabel.text = [dict objectForKey:@"second_property"]; 
+0

感謝它很好,但我也添加「self.table_dom」,使它工作100%,因爲它曾經崩潰時,我滾動tableview(在cellForRowAtIndexPath方法) – krifur 2010-11-23 14:57:11

+0

是的,這可能是最簡單的方法。否則,您也可以執行[table_dom retain]。 – 2010-11-23 15:01:48

2

爲什麼不是你可以在對象的形式訪問,以便爲這個 刪除

[fetchRequest setResultType:NSDictionaryResultType]; 

[fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:@"first_property",@"second_property",nil]]; 

then now

你的實體的個
table_dom = [managedObjectContext executeFetchRequest:fetchRequest error:&error]; 

有table_dom對象,以便您使用此陣 提取物和訪問這兩個屬性first_property和second_property 通過簡單地使用。運營商。

相關問題