Nosrettap
Nosrettap

Reputation: 11320

How to create a dynamic array that keeps its size in objective c?

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.

Upvotes: 2

Views: 2989

Answers (2)

Jason Kulatunga
Jason Kulatunga

Reputation: 5894

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"];

Upvotes: 8

Christian
Christian

Reputation: 1714

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.

Upvotes: 3

Related Questions