Padin215
Padin215

Reputation: 7484

Altering an instance NSArray

I have an instance array that I will end up changing depending on user settings. I set the to a immutable NSArray:

@property (strong, nonatomic) NSArray *pointArray;

When i need to change the array, i've been doing this:

-(void)changePointArray
{
    NSMutableArray *tempArray = [NSMutableArray arrayWithArray:self.pointArray];

    // Make changes

    self.pointArray = [NSArray arrayWithArray:tempArray];
}

Is this acceptable practice or am i creating a leak? Should i just typecast it instead:

self.pointArray = (NSArray *)tempArray;

or do even need to worry about setting a NSMutableArray to a NSArray?

self.pointArray = tempArray;

Upvotes: 0

Views: 152

Answers (4)

Hot Licks
Hot Licks

Reputation: 47759

What are your concerns? For such a scenario one might be concerned with atomicity, security against someone else modifying the array, neither, or both. If you're concerned with neither, just make your property an NSMutableArray and modify it in place.

If you're worried about atomicity, you should make a copy, modify the copy, then swap it in (but, of course, all users of the object must know to make their own private copy of the pointer for a series of "atomic" references, vs re-referencing the property for each reference).

For security you should both make the array an immutable NSArray and make the property read-only.

Upvotes: 2

Daniel Rinser
Daniel Rinser

Reputation: 8855

No, there is no leak (with respect to memory management).

Your code is absolutely ok if your goal is to not expose the mutual array in your public interface.

If, however, you don't care about abstraction here (or if that property is not public), it would be easier to just declare the property of type NSMutualArray * in the first place.

Upvotes: 1

Ezeki
Ezeki

Reputation: 1519

You don't have to worry about this self.pointArray = tempArray; because NSMutableArray is a subclass of NSArray. Maybe a little bit more memory is allocated for NSMutableArray but that is not a problem at all - don't worry about that.

And of course you still can do self.pointArray = [NSArray arrayWithArray:tempArray];

You would have problems in the opposite case though if you had

@property (strong, nonatomic) NSMutableArray *pointArray;

and you were trying to do self.pointArray = tempArray; were tempArray is NSArray*

and if you try to do self.pointArray = (NSMutableArray*)tempArray; IN THAT CASE you would have problems

Upvotes: 1

Midhun MP
Midhun MP

Reputation: 107231

If the content can be changed or modified then the best solution is to use an NSMutableArray instead of NSArray.

If you have any specific reason for using NSArray then the following code is the best solution.

self.pointArray = [NSArray arrayWithArray:tempArray];

Upvotes: 0

Related Questions