Question

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";
}
Was it helpful?

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

OTHER TIPS

@synthesize in Objective-C works similarly to automatic property syntax in C#, in that both generate the minimal required syntax for creating property getters/setters. In both languages, if you want custom functionality, you need to implement them manually.

I really like Ryan Wersal's answer of using a #define to roll your own macro. You'd still have to write the method yourself, but you only do it once.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top