ios - 如何从字典 [Objective-C] 中的其他键中删除对象?

标签 ios objective-c iphone algorithm

我有一个 NSMutableDictionary 如下:

{ 0 = (1,5,6); 1 = (0,2,6,7); 2 = (1,7,8); 5 = (0,6,10,11); 6 = 
(0,1,5,7,11,12)}; 

格式为{NSNumber:NSMutableArray}

我想删除每个键中的每个 0 或值为“0”的键。有什么办法吗?

预期的结果是:

{ 0 = (1,5,6); 1 = (2,6,7); 2 = (1,7,8); 5 = (6,10,11); 6 = 
(1,5,7,11,12)};

我正在寻找一个优雅的解决方案。

最佳答案

假设您的 NSMutableArray 是一个 NSNumber 数组,并且在此改进中删除了键 0

改进

NSMutableDictionary * dict = [NSMutableDictionary dictionary];
dict[@0] = [NSMutableArray arrayWithObjects:@0,@10, nil];
dict[@1] = [NSMutableArray arrayWithObjects:@0,@10, nil];
dict[@2] = [NSMutableArray arrayWithObjects:@0,@7,@10, nil];

int valueToRemove = 0; //change this value for what you need
for (NSNumber * key in dict.allKeys) {
    if([key intValue] == valueToRemove) {dict[key] = nil;}
    dict[key] = [dict[key] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"intValue != %i",valueToRemove]];
}

NSLog(@"%@",dict);

控制台日志

2017-07-28 02:18:21.257 ArrayProblemQuestion[76557:1576267] {
    1 =     (
        10
    );
     2 =     (
         7,
         10
     ); }

如果你只想为某些键循环

NSMutableArray * array = [NSMutableArray arrayWithObjects:@1,@3,@0, nil];
    for (NSNumber * key in [dict.allKeys filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"intValue IN %@",array]]) {
        NSLog(@"%@",key);
    }

这将只针对 array 中包含的键循环

希望对你有帮助

关于ios - 如何从字典 [Objective-C] 中的其他键中删除对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45365891/

相关文章:

ios - 如何在plist中写入数据?

ios - 更新自定义嵌套 plist 中的值

ios - Swift - 如何发送内容类型为 "x-www-form-urlencoded"的 POST 请求

iphone - PSTCollectionView 因 EXC_BAD_ACCESS 崩溃

ios - 从 YouTube JSON 数据 Objective C 获取缩略图

iphone - UITextView 作为自己的委托(delegate)意味着无限循环

ios - 在缩放手势时重新缩放圆 View

ios - 通过内容拥抱优先级解决歧义

ios - 找不到 'NSFetchedResultsControllerDelegate' 的协议(protocol)声明

iphone - 基于视觉的增强现实 Objective-C 库