Yet another instance variable, property question


As it was already discussed in other posts, we have these declarations in the interface file.

NSMutableArray *_assets;

@property (nonatomic, copy) NSArray *assets;[/b]

But there are methods addAsset and removeAsset which directly access the mutable array. Other objects can access these methods and add and remove assets. Then what is the use of having mutable and immutable arrays?

Please explain. Thanks a lot.

The mutable array instance is for internal use and the immutable array property is for external use.

In a real-world application, it is conceivable that those methods (addAsset, removeAsset and setAssets: etc.) could do more: for example, they can enforce certain restrictions.

The examples in the book are not designed to teach real-world application programming, and thus are kept simple.

Hi ibex10,

Thank you very much for the explanation.

Is it also the case with setAssets method?

Another object can call this method and easily replace the internal mutable array with another array. Or am I missing anything?

Also, what is the practical use of this setAssets method? Who needs it?

Thanks again.

A lot of comments about this chapter yes it’s challenging !! I just can’t seem to get my mind around what those first two methods do in BNR employee.m I finally tried commenting out the first two methods The one that starts - (void)setAssets:(NSArray *)a and the - (NSArray *)assets The program runs fine without them. Also I commented out the @property NSArray *assets and it works. why does this work without the two methods? I don’t see when those two methods were ever called who calls setAssets ? the -(void)addAsset:(BNRAsset *)a is called… Any insight is greatly appreciated!!!

1 Like

Can we see your code?

Was confusing then in the next couple chapters they show how to use class extensions to hide mutability which seems like the way to do this.