Assets declared as variable & property in same file

Can anyone clarify why assets are declared in the same file as both of the below:

_assets

and

@property *assets

I get that one is a NSArray and one is NSMutableArray but not sure why

  • Both are declared in same file with same names?
  • Why we can’t use the setter getters for the NSArray OR the regular access with the @property variable pointer?
  • What is the role of the copy property. I’ve read up on it somewhere but would appreciate clear simple explanation on this and above.

Thanks

PS this is also related and will post here. Why are we creating copies (copy and mutableCopy) on the method and just not for instance just using setters and getters on a NSMutableArray for instance?

@implementation BNREmployee

// Accessors for assets properties

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

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

Anyone, please?

Would simply like clarity, for instance on why we need to use copy etc and not just create new instances on regular way? And the other points

@triunion the approach taken here is to control access to the properties. In this case the @property *assets has public access, but the _assets variable is private, meaning that it can’t be accessed outside of itself. We are using the default setter / getter on the @property *assets to set our private property, and to return an immutable copy of the array instead of a direct reference to the array itself. This ensure that no other object is able to modify that array except for the BNREmployee class after it has been set. We are using mutableCopy / copy to alter the mutability here, so when it is set, we are converting the array so that it can be modified internally, and when someone gets the value, we are making it immutable, implying in the code that we don’t want outside objects to make modifications. Now obviously, someone could convert that back to a mutable array, but because it is a copy, it will not effect the assets property inside of the BNREmployee object.

For instance

BNREmployee * employee = [[BNREmployee alloc] init];
employee.assets = @[@"asset 1", @"asset 2"];
NSMutableArray * assets = [employee.assets mutableCopy];
[assets addObject: @"asset 3"];
NSLog(employee.assets);   //["asset 1", "asset 2"]
NSLog(assets);            //["asset 1", "asset 2", "asset 3"]

Does all of that make sense?

1 Like

Excellent explanation :slight_smile:

Thank you jbullock.

Appreciate the response on this. If anything still isn’t clear I can reply back.