NSPredicate在数组数组上 [英] NSPredicate on array of arrays

查看:101
本文介绍了NSPredicate在数组数组上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,在打印出来时看起来像这样:

I have an array, that when printed out looks like this:


(
        (
        databaseVersion,
        13
    ),
        (
        lockedSetId,
        100
    )
)

是否可以使用NSPredicate(可能通过数组中的索引)对其进行过滤.像这样:给我所有元素0为'databaseVersion'的行吗?我知道,如果我有一组字典,可以使用与此处类似的谓词来完成此操作. ,但是我发现当使用字典并存储大量数据时,我的内存消耗上升了(从〜80mb增加到〜120mb),因此,如果可能的话,我将保留该数组.关于如何做到这一点有什么建议吗?

Would it be possible to filter this using an NSPredicate (potentially by the index in the array). So something like: give me all rows where element 0 is 'databaseVersion'? I know that if I had an array of dictionaries I could do this with a predicate similar the one found here, but I found that when using dictionaries and storing a large amount of data, my memory consumption went up (from ~80mb to ~120mb), so if possible I would to keep the array. Any suggestions on how this might be done?

推荐答案

这可以在谓词中使用"SELF [index]"来完成:

This can be done using "SELF[index]" in the predicate:

NSArray *array = @[
    @[@"databaseVersion", @13],
    @[@"lockedSetId", @100],
    @[@"databaseVersion", @55],
    @[@"foo", @"bar"]
];

NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF[0] == %@", @"databaseVersion"];
NSArray *filtered = [array filteredArrayUsingPredicate:pred];
NSLog(@"%@", filtered);

输出:

(
        (
        databaseVersion,
        13
    ),
        (
        databaseVersion,
        55
    )
)

或者您可以使用基于块的谓词:

Or you can use a block-based predicate:

NSPredicate *pred = [NSPredicate predicateWithBlock:^BOOL(NSArray *elem, NSDictionary *bindings) {
    return [elem[0] isEqualTo:@"databaseVersion"];
}];

这篇关于NSPredicate在数组数组上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆