Re: NSMutableArrays and Integers
Re: NSMutableArrays and Integers
- Subject: Re: NSMutableArrays and Integers
- From: Phill Kelley <email@hidden>
- Date: Mon, 17 Mar 2003 19:23:29 +1100
>
Is it possible to add integer values to an NSMutableArray object? I in
>
particular, would like to add the counter of a for loop in the
>
NSMutableArray object. I tried to convert the integer into its charValue,
>
string value, as well as added another integer counter that moves 1:1 with
>
the for loop counter, but all efforts were in vain. Could someone please
>
guide me? Would these added integer values be obtained by the method,
>
[receiver objectAtIndex: index]?
Example code:
NSMutableArray * array = [NSMutableArray array];
NSNumber * num;
int j;
for (j=0;j<10;j++) {
// turn the number into a numeric object
num = [NSNumber numberWithInt:j];
// add the numeric object to the array
[array addObject:num];
}
Compressed example:
NSMutableArray * array = [NSMutableArray array];
int j;
for (j=0;j<10;j++) {
// add the numeric object to the array
[array addObject:[NSNumber numberWithInt:j]];
}
Both examples do exactly the same thing.
The first example is useful as a way of understanding what happens during
memory allocation. Both the NSMutableArray and NSNumber are created via
"factory methods" and are auto-released.
When the NSNumber object is added to the NSMutableArray, it is sent a
retain message. Similarly, when the NSMutableArray is eventually released,
all objects it references will also be released.
So, if you want the NSMutableArray (and all the NSNumbers it references) to
hang around past the end of the current event cycle, you will need to send
it:
[array retain];
and then remember to send it one of the following once you have finished
using it:
[array release]; // either "go away now"
[array autorelease]; // or "go away at the end of the event cycle"
Probably the other thing you'll want to do is to retrieve the "int" form of
the numbers from the NSNumber object. Assuming "array", "num" and "j" still
exist, consider this:
int k;
for (j=0;j<10;j++) {
// obtain a reference to the numeric object
num = [array objectAtIndex:j];
// retrieve the bunary value
k = [num intValue];
}
the short-hand form of the two statements inside the for loop is:
k = [[array objectAtIndex:j] intValue];
I hope this helps.
Regards, Phill
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.