Only @synthesize is required to override getter

I want to use getter for lazy instantiation and leave the default installer.

Is @synthesize necessary?

Why?

@interface Foo() @property (strong, nonatomic) NSObject *bar; @end @implementation Foo - (NSObject *)bar { if(!_bar) _bar = [[NSObject alloc] init]; return _bar; } @end 

Update: I changed the name of the variable and class because it was confusing. From decks and cards to Foo and bar.

+7
objective-c getter-setter xcode5 synthesize
source share
3 answers

No, you only need to explicitly synthesize (get synthesized ivar) if you explicitly implement all access methods (both getter and setter for readwrite properties, but only getter properties for readonly ). You wrote a getter for this readwrite property, but not a setter, so ivar will still be synthesized for you. Thus, since your code is worth it, you do not need to explicitly @synthesize .

If you created this readonly property, then the implementation of the getter will not allow you to automatically synthesize your ivar. Similarly, since this is readwrite , if you have implemented both getter and setter, you will need to synthesize ivar (if you want to).

+16
source share

Do not use lazy initialization in this way. The deck is useless without cards, and thus lazy initialization buys you nothing but indefinite CPU consumption whenever there may be a first call to this recipient. Fortunately, just creating a mutable array costs nothing (this is also a reason not to use lazy initialization).

In addition, vending a volatile collection violates encapsulation. The deck should contain all the logic to determine which set of cards it contains and in what order. By acquiring a modified collection, the external bit of code can reverse this order behind the deck.

Besides this, what else does it mean to β€œinstall” deck cards? Hiking along this route seems to cause all the logic involved in keeping the deck out of the Deck class, asking why the deck is nothing more than a plain old array in any class using the deck.

+5
source share

In iOS 7, you usually don't need to synthesize. If you need a custom getter, just define it. You will receive a free set of default settings.

0
source share

All Articles