Search code examples
objective-cpropertiesgettersynthesizer

Objective C - Custom @synthesize?


Is it possible to somehow create a custom @synthesize to generate custome getter, setters ??

For example:

@interface
@property (nonatomic, retain) MyObject *object;
@end

@implementation
@lazyInitialize object;
@end

And then somehow define @lazyInitialize to generate a lazy initializer method

//@lazyInitialize

- (id)"property name"
{
   if (!"property name")
   {
      "property name" = [[["property name" class] alloc] init];
   }
   return "property name";
}

Solution

  • You could try something different, though. I wouldn't have thought of this more than a couple days ago, but I happened to be reading Cocoa With Love. In the post linked, he discussed how he made a #define macro that would "generate" the entire class for a singleton into wherever you called the macro from. You can download his code for this (may give ideas on your own implementation).

    Perhaps something like (Warning: Untested Code Ahead):

    #define SYNTHESIZE_LAZY_INITIALIZER_FOR_OBJECT(objectName, objectType) \
    \
    - (objectType *)objectName \
    { \
        if(!objectName) \
        { \
              objectName = [[objectType alloc] init]; \
        } \
        return objectName; \
    } \
    \
    - (void)set##objectName:(objectType *)value \
    { \
        [value retain]; \
        [objectName release]; \
        objectName = value; \
    }
    

    would work? I apologize that I don't have time to properly test it for you, so take that as fair warning that this isn't a quick copy/paste solution. Sorry about that. Hopefully it is still useful! ;)


    Example Usage

    This should work, again Warning: Untested Code Ahead:

    Header

    // ....
    @interface SomeClass : NSObject {
        NSObject *someObj;
    }
    @end
    

    Implementation

    @implementation SomeClass
    // ....
    SYNTHESIZE_LAZY_INITIALIZER_FOR_OBJECT(someObj, NSObject);
    // ....
    @end