Pwner
Pwner

Reputation: 3785

How to declare a property that has no physical backing in Objective-C?

Say I have a property that has no physical backing. That is, it has no internal pointer. An example setter and getter would be:

- (void)setImage:(UIImage*)image
{
    self.imageView.image = image;
    [self setNeedsLayout];
}

- (UIImage*)image
{
    return self.imageView.image;
}

How would I declare the property in the header file to make it clear to other co-workers that this property has no physical backing?

@property(nonatomic, ????) UIImage* image;

I know that if I use copy, assign, or strong, it makes no difference and my code still works. But it is not clear to other people reading the code what my intentions are.

Upvotes: 1

Views: 85

Answers (3)

jscs
jscs

Reputation: 64002

Clients of this class have no reason to know -- indeed, should not care -- how the class stores any of its data.

They should treat this property just as they treat any other property, whether it actually has a backing ivar or not. All they need to know is how to get and set it, and whether the class will take ownership when the property is set.

In this case the class has an (indirect) owner relationship to the image, so strong is the correct choice from the ownership specifiers.

@property (strong, nonatomic) UIImage * image;

Upvotes: 0

Ben Zotto
Ben Zotto

Reputation: 71008

You can declare it only as either readonly or readwrite. The compiler won't generate an instance variable (storage) for it, if you never use it. See also How can I declare a @property but prevent its ivar from being created? (and look at Apple's doc here and scroll to "You Can Implement Custom Accessor Methods") If you really want to specify a retain type, then objects are generally retained--as indeed is yours-- so "strong" is fine, although it will be ignored by the compiler (which you've seen, because any of them work the same).

Design-wise, it's not actually important (or desirable) to indicate to users of the class that there's "no storage" for it. Why should they care, or behave any differently? External to the object, it should just look like any other property, no matter how it is derived.

Upvotes: 1

Cyrille
Cyrille

Reputation: 25144

I'd say strong, because internally the imageView has a strong link to its image:

@interface UIImageView : UIView
[...]
@property(nonatomic,retain) UIImage *image;                                                     
[...]
@end

Upvotes: 1

Related Questions