2011-03-09 3 views
0

I 객체 (JSON 객체)의 배열을 데에서 하위 배열을 얻기 위해 블록을 사용하여 자사의 조용한 혼란이 각 개체는 다음과 같은 특성입니다 : 객체의 그 배열에서아이폰 - 배열

{ 
     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

것 같아요, 당신은 그런 당신이 무엇을 요구하기위한의

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

과 같을 것이다

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

같이있는 NSArray의 방법을 사용하여 의미,하지만 난 차라리 filteredArrayUsingPredicate:을 다음과 같이 사용하십시오 :

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

일부 블로그에서는 사용법이 오히려 술어를 사용한다고 말합니다. 왜 "predicate"을 사용하여 하위 배열을 얻고 싶습니까? 그리고 귀하의 블록 코드에서 "잘못된 정수를 초기화하는 정수 'int', 예상 블록 포인터"오류가 발생했습니다. json 데이터에 문제가 있습니까? – Satyam

+0

내 프로젝트는 대상 OS <4.0을 사용하므로 블록을 사용할 수 없습니다. – Jilouc

+0

정수 "int ', 예상 블록 포인터"를 초기화하는 중 잘못된 변환이 발생했습니다. 우리의 비교가 잘못 되었습니까? – Satyam