Search code examples
objective-ciphonensmutablearraynsmutabledictionary

NSMutableArray addObject using value and key


I found some codes like this:

for (int i = 0 ; i < pinyin_array.count; i++) {
    [pinyins_arr addObject:@{k_PINYIN : pinyin_array[i]}];
}

where pinyins_arr is a NSMutableArray and Kk_PINYIN is a NSString. I am not sure if this is correct or not. I think it should be a NSMutableDictionary to add object of key and value pair. If this is true, the same key will be used for multiple values, what is the final array like?


Solution

  • The @{} syntax is shorthand for creating an NSDictionary. The second line could be verbosely re-written as:

    [pinyins_arr addObject:[NSDictionary dictionaryWithObject:pinyin_array[i]] forKey:k_PINYIN]

    You are adding NSDictionary objects to your NSMutableArray, so you will have an array of dictionaries which all have the same key. It is correct, if this is what you want.