我有一个 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/