tags:

views:

55

answers:

2

Is there a way to make this call in dot notation?:

[someSwitch setOn:YES animated:YES]
+1  A: 

Make a custom class for someSwitch:

@interface MySwitch : UISwitch
@property (assign) BOOL animatedOn;
@end

@implementation MySwitch
-(BOOL) animatedOn { return [self isOn]; }
-(void) setAnimatedOn:(BOOL)inOn { [self setOn:inOn animated:YES]; }
@end

Then use it:

someSwitch.animatedOn = YES;

Setting a property through dot notation is limited to a single argument. However, getters and setters need not map to actual members. All the Apple setters with an animated: variant default to not animating when used with dot notation.

drawnonward
A: 

@drawnonward's answer is a good one. The question is why you'd want to do that.

The beauty of dot notation for accessing the getters and setters of synthesized object properties is that you can THINK of the dot-notated properties as data fields. Behind the scenes there's method call stuff happening, but as you write, it feels like you're talking about the object's data fields directly.

I've watched several new iPhone developers (including the one I'm training now) getting really confused about when to dot-notate and when to do an [object message]. The bottom line of it is, dot-notation is for accessing data fields (while knowing that it's really a convenient piece of syntactical sugar around synthesized getter and setter methods) and method calls are for instructing objects to do something. And obviously "setValue" is a possible something to do, and that's totally valid too.

Dan Ray
In the general case, giving a side effect to assigning data can be good design. For example, assigning a new value to a control will usually call `setNeedsDisplay` as a side effect. In this particular case I would agree that animation is not a good side effect candidate.
drawnonward
Yeah, @drawnonward, that may be what I was reacting to about that example. I don't mind overriding a setter to have side-effects, but animations (and really anything else about the specifics of UI and rendering) ought to happen in a way that's uncoupled from data-management code, in my view. That's different from setting needsDisplay, which is pretty close to a data property.
Dan Ray