Person init method incorrectly assigning to ivar not prop


#1

In the Person classes, -init method, you’re setting the expectedRaise and personName ivars directly, not using the properties.

This has no side effect for the float but does for the string, which has its property attribute set to copy not retain.

It would probably be easier to see if you used different names for the ivars and properties in the example.

Illustrative code (with ivars and properties given different names):

[code]-(id)init
{
self = [super init];
if (self) {
self.expectedRaise = 0.05;
NSMutableString *p = [NSMutableString stringWithString: @“Albus”];

    // Assigning to the instance variable directly,
    // bypasses the setter and does *not* copy.
    // (ARC hides this somewhat since we don't get a memory issue 
    // as it is still retained.)
    _personName = p;
    
    NSLog(@"Person name: %@", _personName);
    
    [p appendString: @" Percival"];

    // As we can see here, since we get not Albus but Albus Percival
    NSLog(@"Person name: %@", _personName);
    
    [p appendString: @" Wulfric"];
    
    // Using the property (with "self"), however, results in the
    // setter being called and the value being copied. 
    self.personName = p;
    
    // Albus Percival Wulfric
    NSLog(@"Person name: %@", _personName);

    [p appendString: @" Brian Dumbledore"];
    
    // Still, "Albus Percival Wulfric"
    NSLog(@"Person name: %@", _personName);
    
}
return self;

}
[/code]

Results in:

2012-01-27 19:58:56.078 RaiseMan[50522:707] Person name: Albus
2012-01-27 19:58:56.083 RaiseMan[50522:707] Person name: Albus Percival
2012-01-27 19:58:56.086 RaiseMan[50522:707] Person name: Albus Percival Wulfric
2012-01-27 19:58:56.087 RaiseMan[50522:707] Person name: Albus Percival Wulfric

hth + great work on the latest edition (as always) :slight_smile: