开发者

assigning NSNumber object to NSString object won't cause any error or warning

开发者 https://www.devze.com 2023-04-12 04:03 出处:网络
I\'ve put NSNumber object into NSDictionary object, and then pop and assign it to a variable declared as NSString instance.

I've put NSNumber object into NSDictionary object, and then pop and assign it to a variable declared as NSString instance.

NSString *test;
NSDictionary *dict = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:1000] forKey:@"key"];

test = [dict valueForKey:@"key"];
NSLog(@"%@, type of %@", test, NSStringFromClass([test class]));

return 0;

After running the above code, I've found that the type of test, declared as (NSString *) is __NSCFNumber. Why did it happen and why compiler did give no warning or errors? Do I have to NSString constructor, such as NSStringWithFormat..., in order to keep test as NSString's开发者_开发技巧 instance?


The reason this did not fail or warn you is because valueForKey: returns an object of type id which you can assign to any Objective-C type. You need to be aware of what type of value you are getting back from your collections to safely use them. In this case you know it contains an NSNumber so you should expect an NSNumber and if you need a string you will need to do the proper conversions.

NSNumber *test = [dict valueForKey:@"key"];
NSLog(@"%@, type of %@", test, NSStringFromClass([test class]));

//If you need a string
NSString *testStr = [test stringValue];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号