Objective C Idioms - Properties, ivars and needsDisplay

Here the situation that I encounter a lot is enough for the template code to be wasteful and sufficient, and I am sure that I cannot be the only one. Is this uniomatic, is there a better way, or should I just do it every time?

@interface SomeUIElement : UIView @property CGFloat insetMargin; // <-- just an example of a UI parameter @end @implementation SomeElement - (void)setInsetMargin:(CGFloat)insetMargin { _insetMargin = insetMargin; [self setNeedsDisplay]; // <-- the only thing that stops it being synthesized } @end 

now this causes a compilation warning that I donโ€™t have a recipient to get rid of what I can add

 - (CGFloat)insetMargin { return _insetMargin; } 

but now he complains that I donโ€™t have ivar (because the specific getter and setter means that it wasnโ€™t created for me), so I need to add

 @interface SomeUIElement () { CGFloat _insetMargin; } 

which means that we have significant overhead, just requiring a forced screen refresh when the property changes.

Is there any way to tell ObjC that I intended to create getter and ivar for it, so I only need to write setter, or (b) the best way to request a display update when a property is associated with a change in appearance?

How does the Apple SDK do this (I assume I have not missed any way to view, say, the source of UILabel)?

+4
source share
1 answer

You can get "partial synthesis" if the property is declared non-atomic:

 @property (nonatomic) CGFloat insetMargin; 

The default value (for unknown reasons) is atomic. To realize this atomicity, both access devices must use the same locking mechanism. However, this mechanism is not disclosed when the methods are synthesized. Therefore, you need to either implement both accesses, or create your own lock, or let the compiler do this and use its lock.

If the property is not atomic, you can explicitly implement any combination of three elements: ivar, setter or getter, and the compiler will take care of the rest. If you want to change the default ivar name (currently the name of the property with an underscore added), you will also need an explicit @synthesize .

+5
source

Source: https://habr.com/ru/post/1495054/


All Articles