2011-03-09 35 views
0

我有對象(JSON對象)的陣列的子陣列 每個對象是以下的性質:iphone - 及其安靜混淆使用塊來獲得從陣列

{ 
     author = "<null>"; 
     category =   { 
      "created_at" = "2011-02-06T18:11:39Z"; 
      id = 4; 
      name = lawyers; 
     }; 
     "created_at" = "<null>"; 
     id = 693; 
     "mobile_user_id" = "<null>"; 
     "rating_count" = 0; 
     status = 1; 
     text = "A brain walks into a bar and says, \"I'll have a pint of beer please. \"The barman looks at him and says \"Sorry, I can't serve you.\" \"Why not?\" asks the brain. \"You're already out of your head.\""; 
     title = "A brain goes to a local bar"; 
    } 

從對象的那些陣列,我想查找類別爲id = 4的對象並創建一個子數組。

有人可以幫我使用塊並從數組中獲取子數組嗎?

回答

2

我想通過「使用塊」,你的意思是使用的NSArray的方法類似

- (NSIndexSet *)indexesOfObjectsPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate 

然後,它看起來像

NSIndexSet *indexes = [yourArray indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) { 
    return (BOOL)([[obj valueForKeyPath:@"category.id"] intValue] == 4); 
}]; 
NSArray *filteredArray = [yourArray objectsAtIndexes:indexes]; 

這對你的要求,但我寧願使用filteredArrayUsingPredicate:像這樣:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"category.id = %@", [NSNumber numberWithInt:4]]; 
NSArray *filteredArray = [yourArray filteredArrayUsingPredicate:pred]; 
+0

有些博客說,使用塊而不是使用謂詞。你爲什麼要用「謂詞」來獲取子數組?和你的塊代碼拋出錯誤「無效的轉換初始化整數'INT',預期的塊指針',有什麼毛病我的JSON數據? – Satyam 2011-03-09 09:05:57

+0

我的項目使用目標OS <4.0,所以我不能使用塊。 – Jilouc 2011-03-09 09:08:17

+0

我得到「無效的轉換初始化整數'int',期望塊指針」,我們的比較有什麼問題? – Satyam 2011-03-09 09:10:00