【问题标题】:NSPredicate returning empty arrayNSPredicate 返回空数组
【发布时间】:2015-01-07 15:32:12
【问题描述】:

我正在尝试过滤“频道”数组以仅查找类型属性为“Twitter”的频道。但是,我尝试使用 NSPredicate 过滤数组时返回一个空数组。这是我的代码:

NSMutableDictionary *officials = [decodedData valueForKey:@"officials"];
NSMutableArray *channels = [officials valueForKey:@"channels"];
NSLog(@"%@", channels);


NSPredicate *twitterPredicate = [NSPredicate predicateWithFormat:@"type = 'Twitter'"];
NSLog(@"%@", [channels filteredArrayUsingPredicate:twitterPredicate]);

这是我应用谓词前后的返回:

之前:

 (
    (
            {
        id = SenatorFeinstein;
        type = Facebook;
    },
            {
        id = SenFeinstein;
        type = Twitter;
    },
            {
        id = SenatorFeinstein;
        type = YouTube;
    }
),
    (
            {
        id = senatorboxer;
        type = Facebook;
    },
            {
        id = SenatorBoxer;
        type = Twitter;
    },
            {
        id = SenatorBoxer;
        type = YouTube;
    }
),

)

之后:

2015-01-07 10:19:31.760 voices[537:66850] ()

我的谓词过滤器有问题吗?我正在使用适用于 iOS 的 Google Civic API。任何建议表示赞赏

【问题讨论】:

  • 问题是你的通道数组中有两个数组。
  • 看起来你有一个包含两个数组的数组,每个数组包含三个字典。您的谓词可能仅过滤顶部数组而未找到任何匹配项,因为它正在过滤的元素(数组)不提供该键。您需要更改逻辑以过滤子数组。

标签: ios objective-c json filter nspredicate


【解决方案1】:

试试这个,它会从通道数组中的数组中获取所有的字典:

NSMutableDictionary *officials =[decodedData valueForKey:@"officials"];
NSMutableArray *channels = [officials valueForKey:@"channels"];
NSLog(@"%@", channels);

NSMutableArray *onlyChannels = [[NSMutableArray alloc] init];
for (NSArray *array in channels)
{
    for (NSDictionary  *dict in array)
    {
        [onlyChannels addObject:dict];
    }
}


NSPredicate *twitterPredicate = [NSPredicate predicateWithFormat:@"type = 'Twitter'"];
NSLog(@"%@", [onlyChannels filteredArrayUsingPredicate:twitterPredicate]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 2021-08-11
    • 2017-02-27
    • 2020-04-01
    • 2019-04-17
    • 2017-04-24
    相关资源
    最近更新 更多