BNRAsset Accessors

I have a question.

Why are the BNRAsset Accessors in the BNREmployee Implementation file?

Thank you.

Dave

I have a similar question around this.

What is the purpose of using mutableCopy and copy in the custom accessor methods in the below implementation:

@implementation BNREmployee

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

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

I understand what these methods do, but leaving this code out of my solution still works the same. Is there a reason or best-practice for getting/setting from copies of the _assets array?

Garth

garrrth

In your own app perhaps it won’t matter but if you’re creating a class that others can access, you will prevent them from changing your array data.

With _assets = a;
both will point to the same memory location, same data. Altering either will alter the same array.

With _assets = [a mutableCopy];
altering assets or a will not alter the same data.

– Dave

I must be dense.
This still is not making sense to me.
Can someone explain these lines of code to me and help me over this hump?
The *)a is a pointer to an NSArray that a contains the assets as set where? and the a becomes a copy of those set assets?
These are basically setters for a non mutable array to become a mutable array or am I just like wayyyy off?? Thanks for any help!

// Accessors for assets properties

  • (void)setAssets:(NSArray *)a
    {
    _assets = [a mutableCopy];
    }

  • (NSArray *)assets
    {
    return [_assets copy];
    }

I’ll answer the above question by restating what I’ve learned in this and other threads in this forum:

 - (void)setAssets:(NSArray *)a
{
_assets = [a mutableCopy];
}

Does two things: it copies and converts the incoming NSArray “a” to the NSMutableArray “_assets”. By copying it, the “outside world” can’t change _assets by changing a.

Replacing the line with “assets = a;” will work, but you’re then exposing _assets to change from outside BNREmployee (bad practice) and you will get a warning that NSArray != NSMutableArray,

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

This also returns a copy of _assets array for the same reason I mentioned above. There doesn’t seem to be a warning that we’re copying an NSMutableArray to an NSArray.