I’m looking at some sample code and I’m puzzled over the lack of declaration of a specific ivar. Hoping someone can help me understand this better:
typedef NSUInteger (^NumberOfItemsInSection)(ViewClass *viewClass, NSUInteger section);
// class declaration
@interface SampleScrollView : UIScrollView
@property (nonatomic, copy) NumberOfItemsInSection itemsSectionBlock;
@end
// class implementation
@implementation SampleScrollView
@synthesize itemsSectionBlock = _itemsSectionBlock;
- (void)setItemsSectionBlock:(NumberOfItemsInSection)itemsSectionBlock
{
// _itemsSectionBlock is not declared any where in the class
// How does the compiler not complain?
_itemsSectionBlock = [itemsSectionBlock copy];
[self reloadData];
}
@end
The instance variable, “_itemsSectionBlock”, is not declared any where and it can just be used in the property’s setter override. How does that work?
It’s part of the modern runtime, and cuts down on the duplication of code – declaring iVars and then declaring properties for those iVars.
It’s handled for you by the
@synthesizeThe modern runtime lets you do other things that you thought you couldn’t do before. For example, you can now declare iVars in the .m file as part of a class extension, which reduces the amount of information you expose in your public interface.
Update
The modern LLVM 4 compiler even lets you do away with the @sytnthesize line. If you declare a property it will auto-synthesize for you and it will even create a backing store with a leading underscore.