Jason
Jason

Reputation: 123

How can I read a NSNumber from an array?

I am trying to put a NSNumber to an array with this:

NSNumber *n = [NSNumber numberWithInt:1];
[[array objectAtIndex:0] setValue:n forKey:@"1"];

Then I have an action, which I want it to print the n.intValue from the array. I wrote it like this:

-(IBAction)action:(id)sender {
NSNumber *n = [[array objectAtIndex:0 ] valueForKey:@"1"];
NSLog(@"%d",n.intValue);
}

The problem is that it is printing 0 instead of 1.

How can I rewrite this to make it work?

Thanks.

Upvotes: 1

Views: 1408

Answers (2)

Mudit Bajpai
Mudit Bajpai

Reputation: 3020

You can simply do like this

NSMutableArray *array=[[NSMutableArray alloc] init];
 NSNumber *n = [NSNumber numberWithInt:1];
 [array addObject:n];
  NSLog(@"%@",[array objectAtIndex:0 ]);

Upvotes: 1

MadhavanRP
MadhavanRP

Reputation: 2830

You are invoking setValue:n forKey:@"1" on the first object of the array. This won't insert the NSNumber object into the array and I don't think whatever object is in that array will respond to that key. So, what you are logging is actually a nil NSNumber object's intValue. Which is why you are getting 0.

What you need to do is use an NSMutableArray and not NSArray. You can insert the NSNumber as

NSNumber *n = [NSNumber numberWithInt:1];
[mutableArray insertObject:n atIndex:0];

and read it

-(IBAction)action:(id)sender {
NSNumber *n = [mutableArray objectAtIndex:0];
NSLog(@"%d",n.intValue);
}

Upvotes: 0

Related Questions