Object Instance Variable and Property

Hello everyone!

Well I cracked my head since the last night in order to figure out this problem, but unfortunately I cannot do so.
So I really hope you all can help me with this.

In the book, under BNREmployee.m, the author writes the following codes:

//Accessors for assets properties
-(void)setAssets:(NSArray *)a
    _assets = [a mutableCopy];

-(NSArray *)assets
    return [_assets copy];

-(void)addAsset:(BNRAsset *)a
    //Is asset nil?
    if(!_assets) {
        //Create the array
        _assets = [[NSMutableArray alloc]init];
    [_assets addObject:a];

The above coding looks fine, but one question strikes me hard:
Why do we need to initialise accessors for assets properties? [-(void)setAssets:(NSArray *)a, -(NSArray *)assets]
Instead of writing the above accessors first, why don’t we write only -(void)addAsset:(BNRAsset *)a?
Because inside -(void)addAsset:(BNRAsset *)a, we could create a NSMutableArray if _assets doesn’t exist, right?
So why do we need to take so much trouble writing -(void)setAssets:(NSArray *)a, -(NSArray *)assets in the first place?

Thank you.

What we’re doing here is hiding the mutability of the array from other objects.

In the header, we’ve declared the property as being of type NSArray. In the implementation, though, it turns out that we’re actually using an NSMutableArray to back the property. Why? Because our object wants to be able to easily mutate (add and remove objects) to the assets array, but doesn’t want outsiders to be able to. This is what we do sometimes when we want a property to be publicly immutable but privately mutable.

Notice that the implementations of the accessors that we’ve written do nothing more than convert the array back and forth between what the public sees (an NSArray) and what we use internally (an NSMutableArray).

I hope that helps.

Hi Mikey!

Yup, your reply really help me a lot to grasp the whole picture, especially this sentence of yours:

[quote]What we’re doing here is hiding the mutability of the array from other objects.

Through that sentence, I understand why we take so much trouble to create the accessors for the property “Assets”.

Thank you!