In Java, I can do that :
int[] abc = new int[10];
for(int i=0; i<abc.length; i++){
abc[i] = i;
}
How can I implement similar thing in Objective C?
I see some answer using NSMutableArray, wt's different between this and NSArray?
Try something like this.
#import <foundation/foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *myArray = [NSMutableArray array];
[myArray addObject:@"first string"];
[myArray addObject:@"second string"];
[myArray addObject:@"third string"];
int count = [myArray count];
NSLog(@"There are %d elements in my array", count);
[pool release];
return 0;
}
The loop would look like:
NSString *element;
int i;
int count;
for (i = 0, count = [myArray count]; i < count; i = i + 1)
{
element = [myArray objectAtIndex:i];
NSLog(@"The element at index %d in the array is: %@", i, element);
}
See CocoLab
NSMutableArray* abc = [NSMutableArray array];
for (int i = 0; i < 10; ++ i)
[abc addObject:[NSNumber numberWithInt:i]];
return abc;
Here,
-addObject:
appends an ObjC at the end of the array.This is actually more similar to the C++ code
std::vector<int> abc;
for (int i = 0; i < 10; ++ i)
abc.push_back(i);
return abc;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With