19

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?

3 Answers 3

18

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

Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't answer how to ASSIGN to a specific index. Only how to read from it.
11
NSMutableArray* abc = [NSMutableArray array];
for (int i = 0; i < 10; ++ i)
   [abc addObject:[NSNumber numberWithInt:i]];
return abc;

Here,

  • NSMutableArray is a "mutable" array type. There is also a constant array super-type NSArray. Unlike C++, ObjC's array is not typed. You can store any ObjC objects in an NSArray.
  • -addObject: appends an ObjC at the end of the array.
  • Since NSArrays can only store ObjC, you have to "box" the integer into an NSNumber first.

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;

Comments

3

I see some answer using NSMutableArray, wt's different between this and NSArray?

NSArray is immutable: it cannot be changed. NSMutableArray is a subclass that is mutable, and adds methods to the array interface allowing manipulation of its contents. This is a pattern seen in many places throughout Cocoa: NSString, NSSet, and NSDictionary are particularly frequent examples that are all immutable objects with mutable subclasses.

The biggest reason for this is efficiency. You can make assumptions about memory management and thread safety with immutable objects that you cannot make with objects that might change out from under you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.