Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Danneman101

macrumors 6502
Original poster
Aug 14, 2008
361
1
Im trying to convert a NSString to an int, and then back again after having added one to it:

Code:
// Get string from settings
NSString *str_Right_Answers = [[NSUserDefaults standardUserDefaults] stringForKey:@"settings_Right_Answers"];

// If not initialized, set it to 0		
if (str_Right_Answers == NULL)	{	str_Right_Answers = @"0";	}
		
// DEBUG: shows inital value to be NULL (and is thus set to "0"), as this setting is not initialized anywhere else.
				
// Convert string to int
int n_Right_Answers = (int)str_Right_Answers;
				
// Increase and convert int to string
str_Right_Answers = [NSString stringWithFormat: @"%d", (n_Right_Answers + 1)];

// DEBUG: Expected value should be 1 (first run) but comes up as 57840 instead.

So instead of getting 1 as a result after first run, Im left with a whopping 57840 instead!? I simply have no idea what to make of that, except perhaps that it might be the numerical value of "NULL"? Still, if thats the case then the value is set to 0 and this wouldnt be an issue.

Any ideas?
 
This:

Code:
// Convert string to int
int n_Right_Answers = (int)str_Right_Answers;

may compile but does not do what you think. At all. Not even close. What you are doing is taking the address of a pointer and assigning it to an int.
 
Code:
// If not initialized, set it to 0		
if (str_Right_Answers == NULL)	{	str_Right_Answers = @"0";	}
Also, you should compare with nil, since this is what stringForKey: returns if "the default does not exist or does not contain a string." As in:
Code:
// If not initialized, set it to 0		
if (str_Right_Answers == nil)	{	str_Right_Answers = @"0";	}
 
Ok, should compare to nil as well then :)

But how do I cast the string to int? My googling-session before gave me this:

Code:
int n_Right_Answers = (int)str_Right_Answers;

..and all other suggestions I stumbled over resulted in compile-errors.
 
You cannot cast an object to a primitive. You need to call a method on the object that returns what you want or use a helper object/function. I'd suggest:

1) Stop coding right now until you do some reading and understand what you are doing. Your code tells me right now you have no idea at all.

2) Read the documentation. There is a very obvious NSString method
 
Argh, that was the function I tried out first, but I must have screwed up the syntax since I got an error.

Code:
int n_Right_Answers = [str_Right_Answers intValue];

Thanks for sending me down the right path :)
 
When you encounter syntax errors, it's best to try to fix them rather than just pursue a different approach. It's almost always easier that way. :)
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.