Stefan
Stefan

Reputation: 1335

int not returning same value from NSString

I have saved value in Singletone as NSString. When I want to convert to int, value is some random number. For example, I am calling NSString *numberCoupons = [Manager sharedInstance].userProfile.numberOfCoupons, po numberCoupons returning normal value: 40.
But problem is in next line, when I want to convert string to value: int coupons = (int)numberCoupons; It is returning some random number, etc. 421414.
What could be the problem?

Upvotes: 0

Views: 78

Answers (3)

CRD
CRD

Reputation: 53000

When you write (int)numberOfCoupons you are asking that the value in the variable numberOfCoupons be cast to the type int.

Now the value in a variable of type NSString * is a reference to an object, that is a memory address. When (Objective-)C casts a reference to an integer type you get back the memory address. This is the “random” value you are seeing.

What you need to do is send a message to the object referenced by the value in your variable requesting that it return an integer value equivalent to itself. NSString has a method intValue for this, so [numberOfCoupons intValue] will do what you wish.

There is a whole family of xValue methods to obtain various integer and floating-point values of different precision/size.

Note: if you have a reference to an NSNumber, rather than an NSString, then exactly the same code will work.

Note 2: if you do have an NSNumber then the cast expression you first tried may return a value which has a completely different magnitude than you might expect for a memory address. This is because some integer values are represented by special tagged addresses which don't actually reference a real object. This is an optimisation you normally would not notice, except when you accidentally cast the reference value to an integer...

HTH

Upvotes: 1

Droppy
Droppy

Reputation: 9721

numerofCoupons is obviously an NSNumber object which is used to store numbers within Objective-C collection classes (NSArray, NSDictionary, etc) as only objects can be stored in them.

To get the wrapped value out of the object use:

 NSInteger coupons = [numberOfCoupons integerValue]

I would recommend redeclaring numberOfCoupons as NSInteger, and not NSNumber, as NSNumber objects are difficult and expensive to manipulate compared to the primitive types they wrap.

If the value needs to go into a collection class then wrap it in an NSNumber object when adding it and unwrap it when removing it.

Upvotes: 1

Paddy
Paddy

Reputation: 764

try int coupons = [numberCoupons integerValue];

Upvotes: 1

Related Questions