使用NSPredicate过滤数组数组

时间:2014-06-05 16:53:05

标签: ios objective-c nspredicate

我上课了#34; SMessage&#34 ;;

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

我也可以上课叫做SDay; SDay可以有很多消息(SMessage);

@interface SDay:NSObject
@property(nonatomic, strong)NSMutableArray *messages;
@end

在决赛中,我有一个共同的课程,我有几天的时间;

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

我正在尝试过滤天数数组并找到messageId = 100的消息(例如);

我不知道如何使用NSPredicate来做到这一点; 谢谢你的回答;

1 个答案:

答案 0 :(得分: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;
    }

}];