Add the @property object attribute to objective-c
Does anyone know how to add additional attribute types to the @property keyword without changing the compiler? Or could anyone think of a different way to generate / create a setter?
Basically, I have many cases in a recent project where it is convenient for objects to lazily create array properties. This is because we have event objects that can have a large number of collections as properties. Subclassing for specific events is not desirable because many properties are separated and this would become a usability nightmare.
For example, if I had an object with an array of songs, I would write a getter like below:
- (NSMutableArray *)songs {
if (!songs) {
songs = [[NSMutableArray alloc] init];
}
return songs;
}
Instead of writing dozens of these getters, it would be really nice to get the behavior through ...
@property (nonatomic, retain, lazyGetter) NSMutableArray *songs;
Maybe some fancy tricks via #defines or something else? Any other ideas?
a source to share
You can always use macros. Even if you changed the compiler, you probably still want to do it in @synthesize instead of @property, since there is no need to post this implementation detail. And with a macro, it's easy to use any init method. Unfortunately macros are unaware of the getter = property attribute.
#define synthesizeLazyGetterWithInit(PROPERTY,TYPE,INIT)\
-(TYPE *) PROPERTY { if ( !PROPERTY ) { PROPERTY=[[TYPE alloc] INIT]; } return PROPERTY; }
#define synthesizeLazyGetter(PROPERTY,TYPE)\
synthesizeLazyGetterWithInit(PROPERTY,TYPE,init)
@implementation MyClass
synthesizeLazyGetter(songs,NSMutableArray)
synthesizeLazyGetterWithInit(other,NSMutableArray,initWithCapacity:0)
@end
Edit:
#define synthesizeLazyGetterOptional(PROPERTY,TYPE,INIT);\
-(TYPE *) PROPERTY:(BOOL)inAllocate { if ( !PROPERTY && inAllocate ) { PROPERTY=[[TYPE alloc] INIT]; } return PROPERTY; }\
-(TYPE *) PROPERTY { return [self PROPERTY:YES]; }\
-(BOOL) PROPERTY##Initialized { return nil != PROPERTY; }
a source to share