fengd
fengd

Reputation: 7569

What's the real type? NSString or NSNumber

I have a NSDictionary that contains data converted from json data, like {"message_id":21}. then I use NSNumber *message_id = [dictionary valueForKey:@"message_id"] to get the data.

but when I use this message_id,

Message *message = [NSEntityDescription ....
message.messageId = message_id;

I got the runtime error, assigning _NSCFString to NSNumber,

so I have to use NSNumberFormatter to do the conversion.

NSString *messageId = [dictionary valueForKey:@"message_id"];
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterNoStyle];
message.messageId = [f numberFromString:messageId];

this code works.

but when I was debugging, I saw message_id of

NSNumber *message_id = [dictionary valueForKey:@"message_id"]

has a valid value, 21.

Can anyone see the problem here?

Upvotes: 1

Views: 4375

Answers (3)

onmyway133
onmyway133

Reputation: 48075

Read here SAVING JSON TO CORE DATA and JSON official page

The JSON standard is quite clear about how to distinguish strings from numbers– basically, strings are surrounded by quotes and numbers are not. JSON web services however, are not always good about following this requirement. And even when they are, they are not always consistent from one record to another.

So if you have receive NSNumber where NSString is preferred, you must inspect and fix yourself

Upvotes: 0

gnasher729
gnasher729

Reputation: 41

What library are you using to do the conversion? {"message_id":21} means that an NSNumber with a value of 21 should be returned as an NSNumber, {"message_id":"21"} should return it as an NSString.

Using a number formatter is total overkill. Use the method "integerValue" which works just fine both with NSString* and with NSNumber* - you will get the integer 21, whether the object is NSString or NSNumber. The formatter code will obviously run into trouble if your object is an NSNumber and not an NSString.

So: message.messageId = [[NSNumber numberWithInteger:[messageId integerValue]];

I'd probably add a category to NSDictionary

  • (NSNumber*)nsIntegerNumberForKey:(NSString*)key

which handles the situations where the key is not present, or where the value is a null value or a dictionary or array, so you can use it everywhere you need an NSNumber with an integer value from a JSON document and have error checking everywhere.

Upvotes: 1

Nic
Nic

Reputation: 2864

You are trying to save a NSString to a NSNumber. If you want it as an NSNumber you can do:

NSNumber *message_id = [NSNumber numberWithInt:[[dictionary valueForKey:@"message_id"] intValue]];

This should solve your problem.

Upvotes: 3

Related Questions