12

I am not sure what I am doing wrong here? I have tried various combinations to try and copy an array into variable mmm. I am trying to learn how to create a 2D array and then run a loop to place init_array into 10 columns.

// NSMutableArray *mmm = [NSMutableArray arrayWithCapacity: 20];
NSMutableArray *kkk = [NSMutableArray arrayWithObjects: @"a", @"b", @"cat", @"dog", nil];
NSMutableArray *mmm; //= [NSMutableArray arrayWithObjects: @"1", @"2", @"3", @"4", nil];

[mmm arrayByAddingObjectsFromArray:kkk];

NSLog(@"Working: %@",[mmm objectAtIndex:3]);

thanks...

so this works from the given answer:

NSMutableArray *mmm = [NSMutableArray arrayWithCapacity: 20];
NSMutableArray *kkk = [NSMutableArray arrayWithObjects: @"a", @"b", @"cat", @"dog", nil];

[mmm addObjectsFromArray:kkk];

NSLog(@"Working: %@",[mmm objectAtIndex:3]);

2 Answers 2

24

arrayByAddingObjectsFromArray: returns a new (autoreleased) NSArray object. What you want is addObjectsFromArray:.

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

2 Comments

do I have to "retain" this to use outside of the scope?
@Kristen Martinson: Object lifetimes aren't really related to scope. You have to retain to keep an object you don't own alive past the draining of the current autorelease pool.
10

arrayByAddingObjectsFromArray: returns a new NSArray that includes the objects in the receiver followed by the objects in the argument. The code you posted there, with mmm unset, will probably just crash since mmm doesn't point to an NSArray object. If you had assigned an array to mmm, then it would return (@"1", @"2", @"3", @"4", @"a", @"b", @"cat", @"dog") — but you don't assign the result to any variable, so it just goes nowhere. You'd have to do something like NSArray *yetAnotherArray = [mmm arrayByAddingObjectsFromArray:kkk].

If you have an NSMutableArray and you want to add objects from another array, use addObjectsFromArray:.

1 Comment

Since the other guy was first with the solution, I had to chose him... but you added more info so i gave you a point

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.