openfrog
openfrog

Reputation: 40735

Is there a way to do lazy initialization of a atomic property without having to write setter and getter by hand?

Apparently it's not possible to use @synthesize when overwriting an atomic property accessor. Xcode 4 will produce a warning.

Now, is there another way of using lazy initialization of atomic properties while still letting Xcode synthesize both getter and setter automatically, without overwriting any of them?

Upvotes: 3

Views: 844

Answers (1)

hypercrypt
hypercrypt

Reputation: 15376

What you need to do is write both the setter and the getter. You can still @synthesize to get the storage. e.g.:

//.h
@property (strong) id x;

//.m

@synthesize x = _x;
- (id)x
{
    @synchronized(self)
    {
        if (!_x)
        {
            _x = [[MyX alloc] init];
        }
        return _x;
    }
}

- (void)setX:(id)x
{
    @synchronized(self)
    {
        _x = x;
    }
}

You may need to do additional memory management without ARC and may want to create a different lock (instead of self) or use a different synchronisation method, but it'll give you the gist.

Upvotes: 6

Related Questions