Domanda

I occasionally override the setters of Objective-C properties, and was wondering. If I change the default behavior of a method drastically, where should I document this in the header? Or should I just use a new method completely?

In my current case, I am setting a view up as a placeholder view in interface builder. Programatically, there will be a way to replace this view with a new view (Either an icon, or an arbitrary custom view). The method to swap out the placeholder view will automatically set the property to the new view, remove the placeholder view from the parent view, add the new view to the parent view, and reposition/resize the new view appropriately.

I came up with three options:

A) Override the setter of the property, and document along with the property:

// Documentation goes here
// The setter of this property actually does <etc>
@property (nonatomic, retain) IBOutlet UIView* placeholderView;

B) Override the setter, and declare it in the header:

// Documentation goes here
-(void)setPlaceholderView:(UIView*)view;

C) Use a completely different method and set the property to readonly:

@property (nonatomic, retain, readonly) IBOutlet UIView* placeholderView;
-(void)replacePlaceholderView:(UIView*)view;

Option C seems appealing, because it makes it quite clear what the method does. It will also be clear that since it is different than a normal setter, it may act differently (which it will). The disadvantage I see here is that it doesn't seem to follow the normal Objective-C trend.

What do you guys think is the cleanest way to do something like this?

È stato utile?

Soluzione

You shouldn't "change the default behavior of a [setter] method drastically" at all. A setter method should set a property, and if it does, you don't need to document the override in the header anywhere, since it does exactly what the user would expect, and the override is an implementation detail that can be documented in the implementation file. Radically changing expected behavior is only going to sow confusion, and is something to avoid. Go with option (C) unless your desired behavior is what a user would reasonably expect to happen when she sets that property.

Altri suggerimenti

In practice, an IBOutlet should only be set during initialization from nib files. If I was to refactor this, I'll declare the properties

@property (nonatomic, weak) IBOutlet UIView *initialPlaceholderView;
@property (nonatomic, weak) UIView *placeholderContainerView;
@property (nonatomic, weak) UIView *currentPlaceholderView;

then rename replacePlaceholderView: to

-(void)updatePlaceholderContainerWithNewView:(UIView*)newPlaceholderView;

This is self-documenting code. You can already assume the behavior just by the property and method names.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top