NSMutableArray *Number=[NSArray arrayWithObjects: @"1", @"2", @"3", @"4", @"5", @"6", nil];
I have an array of interger and need to read them one by one. Can anyone please tell me how to code it?
NSMutableArray *Number=[NSArray arrayWithObjects: @"1", @"2", @"3", @"4", @"5", @"6", nil];
I have an array of interger and need to read them one by one. Can anyone please tell me how to code it?
Actually, you have an array of NSStrings.
Note also that assigning an NSArray instance to an NSMutableArray* reference doesn't make much sense.
In any case, you could:
for(NSString *foo in numberArray) {
int i = [foo intValue];
....
}
Note that you should name variables starting with a lower case letter. Prevents confusion and conflicts with class names (what if you wanted to create a class named Number
later?).
As an aside you should use:
NSMutableArray *numStrings=[NSMutableArray arrayWithObjects: @"1", @"2", @"3", @"4", @"5", @"6", nil]
;
The complier will let you assign a NSArray to an NSMutableArray but if you try to send it NSMutableArray specific messages, it may crash.
This is how you enumerate array, NSArray is immutable, of integers:
NSArray * numbers = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:4],
[NSNumber numberWithInt:5],
[NSNumber numberWithInt:6],
[NSNumber numberWithInt:7],
nil];
// now print out
id obj;
NSEnumerator * enumerator;
enumerator = [numbers objectEnumerator];
while ((obj = [enumerator nextObject])) NSLog(@"%@", obj);
This is how you add integers dynamically to an array, NSMutableArray, (and then print the array):
NSLog(@"\ndynamically add integers:");
NSMutableArray * num2 = [[NSMutableArray alloc] init];
int i;
for ( i = 0; i < 10; ++i) [num2 addObject:[NSNumber numberWithInt:i]];
// now print out
enumerator = [num2 objectEnumerator];
while ((obj = [enumerator nextObject])) NSLog(@"%@", obj);
Output from both:
2010-01-27 14:51:40.307 x[5566] 1
2010-01-27 14:51:40.308 x[5566] 2
2010-01-27 14:51:40.308 x[5566] 4
2010-01-27 14:51:40.308 x[5566] 5
2010-01-27 14:51:40.308 x[5566] 6
2010-01-27 14:51:40.308 x[5566] 7
2010-01-27 14:51:40.308 x[5566]
dynamically add integers:
2010-01-27 14:51:40.308 x[5566] 0
2010-01-27 14:51:40.308 x[5566] 1
2010-01-27 14:51:40.308 x[5566] 2
2010-01-27 14:51:40.308 x[5566] 3
2010-01-27 14:51:40.308 x[5566] 4
2010-01-27 14:51:40.308 x[5566] 5
2010-01-27 14:51:40.308 x[5566] 6
2010-01-27 14:51:40.308 x[5566] 7
2010-01-27 14:51:40.308 x[5566] 8
2010-01-27 14:51:40.309 x[5566] 9