Besides that it's exactly the same?
It depends on what setTmp: does. You seem to assume that it only ever releases the current pointed at object and sets the pointer to the new object. There is nothing preventing a programmer writing all sorts of actions into setTmp:
In general one object should
never have direct access to the state variables on another object. So what this means is that an object can call tmp=whatever to set it's own property or instance variable but another object should never call that. Other objects should always call setTmp: as they should not make assumptions about the internal state of the other object.
If we look at a concrete example:
Code:
@interface Rectangle
{
int width;
int height;
int area;
}
-(void) setWidth:(int) newWidth;
-(void) setHeight:(int) newHeight;
-(int) area;
@end
Note that whilst I've used primitive types here this holds true for objects too.
In this case we might think that the implementation of area calculates the area when called. But this is not necessarily true and we cannot make this assumption from outside the object. It's just as possible that setting width or height (via setWidth: or setHeight

calculates the area at that point and stores it in the ivar.
So if we assume that the implementation of Rectangle is as below:
Code:
@implementation Rectangle
-(void) setWidth:(int) newWidth
{
width = newWidth;
area = width * height;
}
-(void) setHeight:(int) newHeight
{
height = newHeight;
area = width * height;
}
-(int) area
{
return area;
}
@end
So if we wanted to create a subclass of Rectangle called Square we could make a mistake and set the width and height directly:
Code:
@interface Square : Rectangle
@end
@implementation Square
-(void) setWidth:(int) newWidth
{
width = newWidth;
height = newWidth;
}
-(void) setHeight:(int) newHeight
{
width = newWidth;
height = newWidth;
}
@end
This is wrong: a call to area will now return the wrong value. In this case calling the setters from the superclass is required to correctly keep the implementation of area. This will work:
Code:
@interface Square : Rectangle
@end
@implementation Square
-(void) setWidth:(int) newWidth
{
[super setWidth:newWidth];
[super setHeight:newWidth];
}
-(void) setHeight:(int) newHeight
{
[super setWidth:newWidth];
[super setHeight:newWidth];
}
@end
Hopefully this illustrates some of the potential issues of not using the setter methods. I would say use them as much as possible: only set the variable directly in the setVariableName: method.
Note that I've typed all this straight into the reply box. It's probably got mistakes.