tags:

views:

85

answers:

3
+1  Q: 

Is this if needed?

This method is generated by Xcode 3.2 using "Accessor defs to clipboard"

- (void)setBodyMass:(int)newBodyMass {
    if (bodyMass != newBodyMass) {
        bodyMass = newBodyMass;
    }
}

Could I just as easily write this as you see below? It seems to be doing a conditional test to save it doing a possible redundant assignment.

- (void)setBodyMass:(int)newBodyMass {
        bodyMass = newBodyMass;
}

cheers -gary-

+2  A: 

I'd do it your way; assigning an int is very cheap. The check makes sense if the assignment is to some large data structure or might have unintended side effects, neither of which is true for int.

fbrereto
+1  A: 

Does the assignment cause something to trigger (event)? Doesn't seem so. You can compare but for a simple int I do not think it's an obligation to verify if the value is the same or not. Of course, if you want to display something to the user concerning that he has entering the same value, you might check the value, otherwise, I would not check it.

Daok
+6  A: 

Normally you do a check like that in a mutator method because you're working with objects that have to be released. Say you have a mutator method without that check:

- (void)setObject:(MyObject *)anObj
{
    [obj release];
    obj = [anObj retain];
}

Imagine (for some reason) you have a chunk of code like this that uses that method:

MyObject *o = [MyObject object];    // Auto-released
[anotherObject setObject:o];
[anotherObject setObject:o];

On Line 1, you can assume o has a retain count of 0 (since it's autoreleased). On Line 2, o has been passed to setObject:, which retains it and stores it in the instance variable obj. Since we're working with pointers, o and obj point to the same object in memory, which now has a retain count of 1.

On Line 3, you pass the same object to setObject: again. But right away in that method, you release anObj, which is the same object that both o and obj point to! This means that o, obj, and anObj have a retain count of 0. When you set obj to [obj retain], you're making obj point to an object that has been released already.

This is obviously bad, so when working with mutator methods that deal with objects, you should always use that guard, which effectively checks to see if obj and anObj point to the same object in memory; if they do, nothing happens.

However, this guard isn't necessary in your example, because you're passing an int -- not a pointer -- and ints, of course, never get released (since they're not objects).

mipadi
Thanks Michael (I am guessing thats right) a very clear exceptional answer, as usual :) many thanks
fuzzygoat