I have this bit of Objective C code, where I am casting a NSString
to an int
:
NSString *a=@"123abc"; NSInteger b=(int) a; NSLog(@"b: %d",b);
And the NSLog
produces this output:
b: 18396
Can anyone explain to me why this is happening?
I was under the impression type casting a string to an integer would get the numerical value from the string.
6 int answer = [@"42" intValue]; 7 NSString *answerString = 8 [NSString stringWithFormat: @"%d", answer]; 9 NSNumber *boxedAnswer = 10 [NSNumber numberWithInt: answer]; 11 NSCAssert([answerString isEqualToString: 12 [boxedAnswer stringValue]], 13 @"Both strings should be the same");
(NSString *) is simply the type of the argument - a string object, which is the NSString class in Cocoa. In Objective-C you're always dealing with object references (pointers), so the "*" indicates that the argument is a reference to an NSString object.
A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.
Objective-C is the primary programming language you use when writing software for OS X and iOS. It's a superset of the C programming language and provides object-oriented capabilities and a dynamic runtime.
You've got integer value of pointer to NSString
object there. To parse string to integer you should do:
NSString *a = @"123abc"; NSInteger b = [a integerValue];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With