user2181948
user2181948

Reputation: 1938

Convert NSDictionary values to NSString

I have an NSDictionary in which the values are of different types, but need to be converted to strings and put back into the original NSDictionary. I have the following so far:

for (id key in myDictionary) {
    id value = [myDictionary objectForKey:key];
    value = (NSString *)[NSString stringWithFormat:@"%@", value];
}

However this is not working - when I print out the type of each value afterwards, they remain the same as before. Can anyone advise?

Upvotes: 4

Views: 4717

Answers (4)

Johnny Rockex
Johnny Rockex

Reputation: 4196

Implementation of description method, credit @Losiowaty

//quick way to create dictionary
NSDictionary * d = @{@"keyA":@(22),@"keyB":[UIView new],@"keyC":@"valueC"};

//create mutable dictionary for new values
NSMutableDictionary * md = [@{}mutableCopy];

//loop through all keys
for (NSString * key in d.allKeys){

    //set value
    md[key]=[d[key] description];

}

NSLog(@"d is %@", d);
NSLog(@"md is %@", md);

Upvotes: 0

Vignesh Kumar
Vignesh Kumar

Reputation: 598

Try this!! You will get good idea! If you want clear option, Could please provide sample dictionary values?

    NSMutableDictionary *myDictionary = [NSMutableDictionary new];
    [myDictionary setObject:@"Vignesh" forKey:@"name"];
    [myDictionary setObject:@(10) forKey:@"rollnum"];
    [myDictionary setObject:@(429) forKey:@"mark"];
    [myDictionary setObject:@(85.8) forKey:@"average"];

    for (id key in myDictionary) {
        NSLog(@"Befor Convert Value %@ - Class %@",[myDictionary objectForKey:key], [[myDictionary objectForKey:key] class]);
        NSString *value = [NSString stringWithString:[NSString stringWithFormat:@"%@",[myDictionary objectForKey:key]]];
        NSLog(@"After Value %@ - Class %@ - Length %@",value, [value class],@(value.length));
    }

Upvotes: 0

Sonam Saxena
Sonam Saxena

Reputation: 56

you can try this

for (id key in myDictionary) {
   if ([key isKindOfClass:[NSString class]]) {
       NSString * value = [[myDictionary objectForKey:key] stringValue];
   }
}

Upvotes: -1

Losiowaty
Losiowaty

Reputation: 8006

When you pass an object into a format string with %@ the objects - (NSString *)description gets called. If you have not overriden this method in your subclass it will print the class name and objects memory address by default. Also, the cast is not needed.

To solve your issue you can either provided custom implementation of description method in your classess, or create your own protocol with a - (NSString *)toString method and implement it where needed.

Upvotes: 2

Related Questions