我有一個分層的NSMutableDictionary對象,我希望能夠刪除層次結構中更深層的字典。有沒有一個快速簡單的方法來做到這一點,例如,一個類似removeObjectAtKeyPath的方法?似乎無法找到一個。NSMutableDictionary在關鍵路徑中刪除對象?
謝謝!
我有一個分層的NSMutableDictionary對象,我希望能夠刪除層次結構中更深層的字典。有沒有一個快速簡單的方法來做到這一點,例如,一個類似removeObjectAtKeyPath的方法?似乎無法找到一個。NSMutableDictionary在關鍵路徑中刪除對象?
謝謝!
沒有內置的,但你的基本範疇方法做得很好:
@implementation NSMutableDictionary (WSSNestedMutableDictionaries)
- (void)WSSRemoveObjectForKeyPath: (NSString *)keyPath
{
// Separate the key path
NSArray * keyPathElements = [keyPath componentsSeparatedByString:@"."];
// Drop the last element and rejoin the path
NSUInteger numElements = [keyPathElements count];
NSString * keyPathHead = [[keyPathElements subarrayWithRange:(NSRange){0, numElements - 1}] componentsJoinedByString:@"."];
// Get the mutable dictionary represented by the path minus that last element
NSMutableDictionary * tailContainer = [self valueForKeyPath:keyPathHead];
// Remove the object represented by the last element
[tailContainer removeObjectForKey:[keyPathElements lastObject]];
}
@end
N.B.這要求該路徑倒數第二個元素 - tailContainer
是響應removeObjectForKey:
,可能是另一個NSMutableDictionary
。如果不是,繁榮!
您可以創建一個類別:
這是高達1級下調:
#import "NSMutableDictionary+RemoveAtKeyPath.h"
@implementation NSMutableDictionary (RemoveAtKeyPath)
-(void)removeObjectAtKeyPath:(NSString *)keyPath{
NSArray *paths=[keyPath componentsSeparatedByString:@"."];
[[self objectForKey:paths[0]] removeObjectForKey:paths[1]];
}
@end
它被稱爲:
NSMutableDictionary *adict=[[NSMutableDictionary alloc]initWithDictionary:@{@"key1" : @"obj1", @"key11":@"obj11"}];
NSMutableDictionary *bdict=[[NSMutableDictionary alloc]initWithDictionary:@{@"key2" : adict}];
NSLog(@"%@",bdict);
NSLog(@"%@",[bdict valueForKeyPath:@"key2.key1"]);
[bdict removeObjectAtKeyPath:@"key2.key1"];
NSLog(@"After category : %@",bdict);
輕微改善,Josh的答案,以處理不包含句keypaths(即keypaths這實際上鍵):
- (void)removeObjectAtKeyPath:(NSString *)keyPath
{
NSArray *keyPathElements = [keyPath componentsSeparatedByString:@"."];
NSUInteger numElements = [keyPathElements count];
if (numElements == 1) {
[self removeObjectForKey:keyPath];
} else {
NSString *keyPathHead = [[keyPathElements subarrayWithRange:(NSRange){0, numElements - 1}] componentsJoinedByString:@"."];
NSMutableDictionary *tailContainer = [self valueForKeyPath:keyPathHead];
[tailContainer removeObjectForKey:[keyPathElements lastObject]];
}
}
我知道這是一個較舊的職位,但我需要發現雨燕2.0相同的解決方案,無法找到一個簡單的答案,我想出了這個解決方案:
public extension NSMutableDictionary {
public func removeObjectAtKeyPath(keyPath:String) {
let elements = keyPath.componentsSeparatedByString(".")
let head = elements.first!
if elements.count > 1 {
let tail = elements[1...elements.count-1].joinWithSeparator(".")
if let d = valueForKeyPath(head) as? NSMutableDictionary {
d.removeObjectAtKeyPath(tail)
}
}else{
removeObjectForKey(keyPath)
}
}
}
我使用遞歸步驟通的keyPath
嘗試'removeValueForKey:' – JonasG 2013-02-27 06:54:16