2

I'm writing an iOS program in objective c and I need an array with the following characteristics:

1) It's shape needs to be decided at runtime.

2) It needs to be able to be stored as a property or a global inside an objective-c class

3) When I insert an object at a specific index it needs to stay at that index. For instance, if I insert at index 5, the object needs to overwrite whatever is at index 5 and do no shifting of this element or any other elements (Similar to how a java array works)

I've looked at NSMutableArray but that doesn't seem to fit what I'm describing above because it shifts elements as you insert. I've also tried NSString *myArray = malloc(10 * sizeof(NSString *)); but this gives me an error regarding requiring a bridged cast. And I don't know what that is.

I'm using ARC, in case that matters.

2 Answers 2

8

1) nameOfMyArray = [[NSMutableArray alloc] initWithObjects:@"obj1", @"obj2", "obj3",nil];

3) Instead of doing an insert operation, why not just do a replace operation?

[nameOfMyArray replaceObjectAtIndex:0 withObject: @"newObject here"];
Sign up to request clarification or add additional context in comments.

5 Comments

He could also fill the array with NSNulls if he knows the size but not the contents initially.
Note: You'd would have to check array bounds first and add a bunch of nils if the array isn't big enough.
Update your code to say initWithObjects:@"obj1", @"obj2", @"obj3", nil]; You are missing a nil at the end, and use the correct code for initialization.
@mkb you can't add nil to a collection. You'd need to add [NSNull null]
@Christian thanks for the comment, I completely forgot about the nil termination, too tired
3

Sounds like you want typical NSMutableArray behavior.

NSMutableArray *arr = [[NSMutableArray alloc] init];
// add a few objects, let's assume there are 10 objects
[arr replaceObjectAtIndex:5 withObject:myObject];

Using the replace method, nothing will be shifted. Your code seems more C-like, and not Objective-C like. I'd recommend reading a book or some documentation to understand how Objective-C objects are supposed to be used -- you'll never malloc an Objective-C object, instead you should be using the alloc class method.

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.