Accessing Instance Variables Directly


#1

In the following code for the description and setContainedItem methods from the book:

- (NSString *)description
{
    NSString *descriptionString = [[NSString alloc] initWithFormat:@"%@ (%@): Worth $%d, recorded on %@",
                                   itemName,
                                   serialNumber,
                                   valueInDollars,
                                   dateCreated];
    return descriptionString;
}

- (void)setContainedItem:(BNRItem *)i
{
    containedItem = i;
    [i setContainer:self];
}

Is it better that we not access the instance variables directly and instead use the accessor methods like below:

- (NSString *)description
{
    NSString *descriptionString = [[NSString alloc] initWithFormat:@"%@ (%@): Worth $%d, recorded on %@",
                                   [self itemName],
                                   [self serialNumber],
                                   [self valueInDollars],
                                   [self dateCreated]];
    return descriptionString;
}

and how would we use brackets on “containedItem = i;” instead of ->:

- (void)setContainedItem:(BNRItem *)i
{
    self->containedItem = i;
    [i setContainer:self];
}

also, assuming that I have declared an instance variable that is a pointer to a Person object like so: Person *someGuy;
is there anyway to do the following with square brackets?

// direct access to instance var
someGuy = [[Person alloc] init];

// or using -> operator
self->someGuy = [[Person alloc] init];

// doesn't work and i understand why, how can we replace the -> above with []'s
[self someGuy] = [[Person alloc] init]

What is the preferred way of doing the above? I’m trying to develop a consistent syntax style early on and would like to avoid directly accessing the instance variables and avoid dot/arrow notation unless working directly with c structs.

Thanks in advance,
john


#2

In general, it’s better not to access the instance variables directly - however, if you are (as in this case) overriding a getter/setter method then you have little choice and must set or get the instance variable directly. There are a couple other places where it’s appropriate to access the instance variables directly - possibly in the init methods.

1
- (void)setContainedItem:(BNRItem *)i is a setter method, this overrides the setter the compiler quietly created for you behind the scenes. It was done in order to set related data in addition to what a setter normally does.

2
Yeah, you can write the description method that way, using messaging rather than direct instance variables.

3
self-> Grumpy Cat says, “No.”

4
Assuming you have declared a @property for someGuy and optionally @synthesised then use
[self setSomeGuy: [[Person alloc] init]];

Hope that helps.