2014-06-05 4 views
1

"SMessage"라는 클래스가 있습니다.NSPredicate를 사용하는 배열의 필터 배열

@interface SMessage:NSObject 
@property(nonatomic)int messageId; 
@end 

또한 SDay라고 불리는 클래스를 사용할 수 있습니다. SDay에 많은 메시지가있을 수 있습니다 (SMessage).

마지막으로 나는 일의 배열을 가지고있는 공통 클래스를 가지고 있습니다;

@interface SCommonClass:NSObject 
@property(nonatomic, strong)NSMutableArray *days; 
@end 

필터 배열을 사용하여 messageId = 100 (예 :) 인 메시지를 찾으려고합니다.

그리고 NSPredicate를 사용하여이를 수행하는 방법에 대한 아이디어가 없습니다. 답변 해 주셔서 감사합니다.

+0

체크 아웃 http://useyourloaf.com /blog/2010/07/27/filtering-arrays-with-nspredicate.html 또한, SO 사람들은 파리 사람들과 조금 비슷합니다. 프랑스어로 말하지 않으면 멋지지만 조금만 시도해야합니다. – danh

답변

0
NSPredicate *p = [NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *bindings) { 

    SDay* day = (SDay*)object; 
    NSMutableArray* messages = day.messages; 
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"messageId == 100"]; 

    if ([messages filteredArrayUsingPredicate:predicate].count == 0) { 
     return NO; 
    } 
    else{ 
     return YES; 
    } 

}]; 


NSArray* result = [common.days filteredArrayUsingPredicate:p]; 

============ 갱신 ===============

NSPredicate *p = [NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *bindings) { 

    SDay* day = (SDay*)object; 
    NSMutableArray* messages = day.messages; 
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"messageID == 100"]; 
    NSArray *filteredMessages = [messages filteredArrayUsingPredicate:predicate]; 
    if (filteredMessages.count == 0) { 
     return NO; 
    } 
    else{ 
     day.messages = [NSMutableArray arrayWithArray:filteredMessages]; 
     return YES; 
    } 

}]; 
+0

술어 블록을 사용자 정의해야합니다. 코드가 작동해야합니다. –

+0

음 ... 약간 잘못되었습니다. 배열을 필터링하려고하면 다음과 같은 결과를 얻습니다. day1에는 두 개의 메시지 (messageId == 100, messageId == 99)가 있습니다. day2는 하나의 메시지 만 가지고 있습니다 (messageId == 100); 결과에서'NSArray * result = [common.days filteredArrayUsingPredicate : p];'필자는 필터링 전과 같은 메시지를 가진 2 일간 배열을 받았습니다. 두 개의 메시지 (messageId == 100)를 가질 때 NSPredicate가 배열을 수신하도록 어떻게 수정해야합니까?; 고맙습니다; – user3711879

+0

SDay 객체의 메시지를 변경하는 것이면 괜찮습니다. 업데이트 된 답변을 참조하십시오. –

관련 문제