在NSMutableDictionary中的键下添加多个对象

时间:2014-09-07 23:41:03

标签: ios objective-c nsarray nsdictionary

我想要实现的目标是,在一个字典中的密钥(帐户)下存储一个值(关键字),然后将该字典存储在另一个字典下,并使用密钥(列表),最后将该字典存储在另一个字典下钥匙(allKeys)。

- (void)addFilterForAccount:(NSString *)account forKeyword:(NSString *)keyword inList:(NSString *)list {

    //Set properties for NSStrings
    account = _accountName;
    keyword = _textField2.text;
    list = _listName;
    //Clear the textField
    _textField2.text = @"";
    //Store this information into a dictionary/array
    _keys = [[NSMutableDictionary alloc] init];
    [_keys setObject:keyword forKey:account];

    _keywords = [[NSMutableDictionary alloc] init];
    [_keywords setObject:_keys forKey:list];

    _filters = [[NSMutableDictionary alloc] init];
    [_filters setValue:_keywords forKey:@"allKeys"];

    //nomenclature would be:
    //
    //_filters[@"allKeys"][@"//listName\\"][@"//accountName\\"]

    NSLog(@"%@", _filters);
}

我有以下代码应该做我想要的,但此时的问题是它不允许多个键。因此,如果我想在一个列表中存储多个关键字,那么当我注销时,它应该是这样的:

2014-09-07 18:31:12.562 Filterfeed[4050:124143] {
    allKeys =     {
        "Breaking News" =         (
                        {
                BreakingNews = romney
                               obama
                               bush
                               clinton;
            }
        );
    };
}

但是现在它只是一个名字,每当我调用这个方法时它就会被替换。

实际打印出来的内容:

2014-09-07 18:31:12.562 Filterfeed[4050:124143] {
    allKeys =     {
        "Breaking News" =         (
                        {
                BreakingNews = romney;
            }
        );
    };
}

1 个答案:

答案 0 :(得分:0)

您希望此方法为:

- (void)addFilterForAccount:(NSString *)account forKeyword:(NSString *)keyword inList:(NSString *)list { 

//Set properties for NSStrings 
account = _accountName; 
keyword = _textField2.text; 
list = _listName; 
//Clear the textField 
_textField2.text = @""; 
//Store this information into a dictionary/array 
_keys = [[NSMutableDictionary alloc] init]; 
NSMutableArray *array = [NSUserDefualts standardUserDefaults] objectForKey: list]; 
[array addObject: keyword]; 
[[NSUserDefualts standardUserDefaults] setObject: array forKey: list]; 
[[NSUserDefualts standardUserDefaults] synchronize]; 
NSMutableArray *array2 = [NSUserDefualts standardUserDefaults] objectForKey: list]; 
[_keys setObject:array2 forKey:account]; 
_keywords = [[NSMutableDictionary alloc] init]; 
[_keywords setObject:_keys forKey:list]; 

_filters = [[NSMutableDictionary alloc] init]; 
[_filters setValue:_keywords forKey:@"allKeys"]; 

//nomenclature would be: 
// 
//_filters[@"allKeys"][@"//listName\\"][@"//accountName\\"] 

NSLog(@"%@", _filters); 
}