Search code examples
objective-cdictionarynsdictionarynsmutabledictionary

append values for key NSMutableDirectory


I'm currently working on objective c code where I have an array I'm looping through and based on the outcomes I add a value to a key.

However when needed I want to append the values for a specific key but I have absolutely no clue on how to achieve this with objective c.

I have written an solution for this in swift before but I can't seem to figure out how to apply the same thing in objective c. Here is what I currently have

-(void)makeDirectory:(NSArray*)aList {
NSMutableDictionary *dic = [NSMutableDictionary new];

for (NSDictionary *entry in aList) {
    NSString *character = @"";
    xbmcMovie *movie = [[xbmcMovie alloc] initWithDictionary:entry];
    NSString *name = movie.Title.stripSpecialCharacters.stripArticle.stripSpaces.stripNumber;
    character = name.character;

    if (![dic objectForKey:character]) {
        [dic setObject:movie forKey:character];
    }
    ///[dic ]
}

}

Here is what I did in swift 3.0

func makeDictionary(_ libraryArray: [songsClass])->[String: [songsClass]]{
    var dic = [String: [songsClass]]()

    for entry in libraryArray {
        var character: String = ""
        var songName = entry.songName.stripSpecialCharacters().stripArticle().stripSpaces().stripNumber()

        guard let char = songName.characters.first?.string() else { return [:] }
        character = char

        if dic[character] == nil {
            dic[character] = [songsClass]()
        }

        dic[character]!.append(entry)

    }
    return dic
}

Solution

  • So if I have understood this correctly, your value in the dictionary is an array which contains a movie, and you want to add to this array, so what you need to do is:

    NSMutableArray *movieArray = [NSMutableArray new];
    [movieArray addObject:movie];
    if (![dic objectForKey:character]) {        
       [dic setObject:movieArray forKey:character];
    }
    
    //If you want to add to this array again then you can do
    
    [movieArray addObject:anotherMovie];
    
    //Or if you need to retrieve the array again
    movieArray = [dic objectForKey:character];
    [movieArray addObject:anotherMovie];
    

    Also your code has

    character = name.character;
    

    where name is a NSString?