Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - Type Casting From NSString to Int

Tags:

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.

like image 587
Jimmery Avatar asked Oct 24 '12 09:10

Jimmery


People also ask

How to convert string to integer in objective-C?

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");

What is NSString in objective-C?

(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.

What is a NSString?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.

What is OBJC?

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.


1 Answers

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]; 
like image 75
Cfr Avatar answered Oct 08 '22 20:10

Cfr