How to add numbers in a mutable array in iPhone?
Asked Answered
E

3

11

I am new to iPhone development. I want a Nsmutable array to hold numbers from 1 to 100. How can I do it? How can I implement in a for loop? Is there any other way to hold numbers in array in iPhone?

Eyeleteer answered 10/4, 2010 at 15:3 Comment(0)
I
25

You can only add NSObject subclasses in Cocoa containers. In your case, you will have to wrap your integers in NSNumber objects:

NSMutableArray *array = [NSMutableArray array];
for( int i = 0; i < 100; ++i )
{
   [array addObject:[NSNumber numberWithInt:i]];
}

To extract the values:

int firstValue = [[array objectAtIndex:0] intValue];
Indulge answered 10/4, 2010 at 15:11 Comment(1)
any idea how we would remove a number added this way if we dont know the index? im trying to use [array removeObjectIdenticalTo:i]; i have also tried [array removeObjectIdenticalTo:[i intValue]] and [array removeObjectIdenticalTo:[NSNumber numberWithInt:i]]Fehr
E
1

Use an NSNumber object:

[NSNumber numberWithInt:1];
Elephantiasis answered 10/4, 2010 at 15:5 Comment(1)
I am a newbie, can u give more code,of how u save the values in a array.Thanks.Eyeleteer
P
0

The short hand solution

NSMutableArray *array = [NSMutableArray array];
for( int i = 0; i < 100; ++i )
{
   [array addObject:@(i)];
}


int intValue = 10;
NSNumber *numberObj  = @(intValue);
Piggyback answered 25/10, 2017 at 21:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.