Ios 基于NSString值的匹配从NSMutableDictionary中删除条目

Ios 基于NSString值的匹配从NSMutableDictionary中删除条目,ios,objective-c,nsstring,nsmutabledictionary,Ios,Objective C,Nsstring,Nsmutabledictionary,在对Instagram API进行网络调用后,我得到一个responseDictionary NSDictionary委托,该委托具有以下键/值结构: { data = ( { bio = "Los Angeles/Orange County Realtor\U00ae \n\U6d1b\U6749\U77f6\U623f\U5730\U4ea7\U7ecf\U7eaa\U4eba\nCall/Text/WhatsApp: (310) 717-13

在对Instagram API进行网络调用后,我得到一个responseDictionary NSDictionary委托,该委托具有以下键/值结构:

{
data =     (
            {
        bio = "Los Angeles/Orange County Realtor\U00ae \n\U6d1b\U6749\U77f6\U623f\U5730\U4ea7\U7ecf\U7eaa\U4eba\nCall/Text/WhatsApp: (310) 717-1321\nEmail: Jxxxcom\nWeChat (\U5fae\U4fe1): xx";
        "full_name" = "xx yy (\U7530\U4f73\U6dfc) Rx Realty";
        id = 25354408;
        "profile_picture" = "http://scontent-a.cdninstagram.com/hphotos-xpa1/outbound-distillery/t0.0-20/OBPTH/profiles/profile_xxx_75sq_1391378894.jpg";
        username = jxxi;
        website = "http://www.Jxghty.com";
    },
profile_picture键通常有一个NSString值,其中包含匿名用户(对于未设置任何配置文件图片的用户)

我希望从我的responseDictionary中删除这些条目,如下所示:

        //Create mutable copy of IG responseDictionary
        NSMutableDictionary *dictCleanAvatars = [responseDictionary mutableCopy];
        NSLog(@"Log dictCleanAvatars after mutableCopy IG response: %@", dictCleanAvatars);

        NSArray *keys = [dictCleanAvatars allKeys]; //get all the keys
        NSUInteger k2 = [dictCleanAvatars count];
        NSLog(@"k2 in dictCleanAvatars before cleanup is: %lu", (unsigned long)k2);

        for (int i = 0; i<k2; i++)
        {

            if ([[dictCleanAvatars objectForKey:[keys objectAtIndex:i]] isKindOfClass:[NSString class]])
            {
                //if its an NSString - don't want an exception if its another type of object
                NSLog(@"Yes, objectAtIndex:i us Kind ofClass NSString for i = %d", i);

                if ([[dictCleanAvatars objectForKey:[keys objectAtIndex:i]] rangeOfString:@"anonymousUser"].location != NSNotFound)
                {
                    NSLog(@"Yes, anonymousUser identified in objectAtIndex:i for i = %d", i);
                    //if object has the key word im looking for
                    [dictCleanAvatars removeObjectForKey:[keys objectAtIndex:i]]; //remove the key
                    NSLog(@"That's dictCleanAvatars after loop %d: %@", i, dictCleanAvatars);
                }
            }
        }
//创建IG responseDictionary的可变副本
NSMutableDictionary*dictCleanAvatars=[responseDictionary mutableCopy];
NSLog(@“可变复制IG响应后的日志日志记录:%@”,dictCleanAvatars);
NSArray*keys=[dictars allKeys]//拿到所有的钥匙
NSU整数k2=[虚拟角色计数];
NSLog(@“清理前的头像中的k2为:%lu”,(无符号长)k2);
对于(int i=0;i

问题是,假设[dictCleanAvatars objectForKey:[keys objectAtIndex:i]]不是NSString?您可能需要先检查它。

如果您查看的唯一字段是profile_picture,我会使用一种更具可读性和可理解性的不太通用的方法

这个代码对我有用

- (void)testExample
{
    NSDictionary *dictionary = @{ @"data": @[ @{ @"bio": @"blah blah", @"profile_picture": @"some stuff anonymousUser other stuff" },
                                              @{ @"bio": @"some other object", @"profile_picture": @"some other profile picture link" }] };
    // dictionary is a mock of the data you provided

    NSArray *data = [dictionary objectForKey:@"data"];
    for (NSDictionary * avatarDict in data) {
        NSMutableDictionary *mdict = [avatarDict mutableCopy];
        id ppid = [mdict objectForKey:@"profile_picture"];
        if ([ppid isKindOfClass:[NSString class]]) {
            NSString *pp = (NSString *)ppid;
            if ([pp rangeOfString:@"anonymousUser"].location != NSNotFound) {
                [mdict removeObjectForKey:@"profile_picture"];
            }
        }
        NSLog(@"altered dictionary: %@", mdict);
    }
}
输出:

2014-08-13 10:53:36.727 test[11981:60b] altered dictionary: {
    bio = "blah blah";
}
2014-08-13 10:53:36.728 test[11981:60b] altered dictionary: {
    bio = "some other object";
    "profile_picture" = "some other profile picture link";
}

如果您试图构建一个包含
数据
键数组中所有内容的数组,但忽略了
profile\u picture
中包含字符串“AnonymousUser”的字典,则可以使用
NSPredicate

NSArray *dataArray = responseDictionary[@"data"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"not (profile_picture contains 'AnonymousUser')"];
NSArray *filteredArray = [dataArray filteredArrayUsingPredicate:predicate];
或者您可以使用
谓词WithBlock

NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(NSDictionary *evaluatedObject, NSDictionary *bindings) {
    return [evaluatedObject[@"profile_picture"] rangeOfString:@"AnonymousUser"].location == NSNotFound;
}];
顺便说一句,如果您已经有一个可变数组,您还可以使用上面的谓词,使用
filtersingpredicate
从中删除条目:

NSMutableArray *mutableDataArray = [responseDictionary[@"data"] mutableCopy];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"not (profile_picture contains 'AnonymousUser')"];
[mutableDataArray filterUsingPredicate:predicate];

另一方面,如果您不想从字典数组中删除整个字典,而是只想删除出现“AnonymousUser”的
profile\u picture
,那么您需要确保不仅数组是可变的,而且它的组成字典也是可变的

最简单的方法是在解析JSON时指定
NSJSONReadingMutableContainers
选项。然后,您只需迭代
NSMutableDictionary
条目,删除包含
profile\u picture
且其中包含“匿名用户”的
profile\u picture
条目:

如果你不能指定<代码> NSJSONRealMutabelCelnistor 选项,当解析JSON并被一个不可变的集合卡住时,你需要对它进行一个可变副本。不幸的是,数组中的一个简单的<代码> MutabelPope<代码>不会使成员字典变为自己,但是你可以使用一个核心基础CAL。l to

CFPropertyListCreateDeepCopy
创建一个包含可变项的可变数组,然后可以修改该数组:

NSMutableArray *mutableDataArray = CFBridgingRelease(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFArrayRef)responseDictionary[@"data"], kCFPropertyListMutableContainers));

然后,您可以使用上面的
for
循环,遍历此数组的字典条目,删除有问题的
profile\u picture
条目。

“但这不起作用”不是问题的描述。为什么不使用KVC查找并删除类似密钥的数据。dictionary.valueForKey(@“data.Anonymous”)?然后尝试使用相同的路径进行删除这不就是从字典副本中删除条目吗?是的,他不能从不变的原始版本中删除它。嗨,罗布:我选择了第三个选项。我喜欢简洁。
NSMutableDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
NSMutableArray *mutableDataArray = responseDictionary[@"data"];

for (NSMutableDictionary *dictionary in mutableDataArray) {
    NSString *profilePicture = dictionary[@"profile_picture"];
    if ([profilePicture rangeOfString:@"AnonymousUser"].location != NSNotFound) {
        [dictionary removeObjectForKey:@"profile_picture"];
    }
}
NSMutableArray *mutableDataArray = CFBridgingRelease(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFArrayRef)responseDictionary[@"data"], kCFPropertyListMutableContainers));