Mahesh Babu
Mahesh Babu

Reputation: 3433

how to validate string in NSUserdefaults

i am getting some id from the web services.

eg:101.

that id i am save in NSUserdefaults and give that value to the string.

Now i need to validate that string like if that string is equal to 0 i need to fire one action and if that value is not equal to 0 i need to fire another action.

for that my code is like this.

NSLog(@"id is%@",[defaults objectForKey:@"id"]);
NSString *intString = [NSString stringWithFormat:@"%d", [defaults objectForKey:@"id"]];

NSLog(@"string %@",intString);
if ([intString isEqualToString:@"0"]) {
    NSLog(@"yes  it is 0");
}
else {
   NSLog(@"No it not eqal to zero");
}

for the first time in console id is 0,string is 0

And if i check second time id is 0, string is 100243248.

i did n't get what this 100243248 value.

I need to check id in NSUserdefaults. if that value is 0 i need to fire one action and if that value is not equal to zero i need to fire another action.

how can i done can any one please help me.

Thank u in advance.


Upvotes: 0

Views: 269

Answers (2)

nss
nss

Reputation: 561

I think that %d takes the int value of whatever you give it. In this case you're passing an object to stringWithFormat. You should instead use [NSString stringWithFormat:@"%@" ....

What's actually happening here is that you're printing out the pointer value of the object returned by objectForKey. The first time this is nil (0), the second time you get 100243248 which is the memory address of something in memory (whatever you stored into NSUserDefaults).

Upvotes: 1

donkim
donkim

Reputation: 13137

Try doing this instead: NSString *intString = [NSString stringWithFormat:@"%@", [defaults objectForKey:@"id"]];

You're not being consistent in what you store in NSUserDefaults, it looks like.

Hope this helps!

Upvotes: 1

Related Questions