Re: How to implement readonly property
Re: How to implement readonly property
- Subject: Re: How to implement readonly property
- From: Marco Tabini <email@hidden>
- Date: Mon, 12 Nov 2012 08:39:52 -0500
> This is completely the wrong way to implement a property. The static variable will be shared between all instances. Here's how you should be doing a lazy loaded var:
>
> @implementation MyClass
> {
> NSDictionary *_someDictionary
> }
>
> - (NSDictionary *)someDictionary
> {
> static dispatch_once_t justOnce;
> dispatch_once(&justOnce, ^
> {
> someDictionary = [[NSDictionary alloc] initWithObjectsAndKeys: …… nil];
> });
> return someDictionary;
> }
I don't think this does what you think it does; my understanding is that dispatch_once will execute only once for the lifetime of an app, so the code you posted will only run once for the first object that requires is, and then never run again, resulting in _dictionary being Nil in all other instances.
I understood the OP's request as wanting to implement a singleton, which, based on your reading, may not be the case. dispatch_once will be fine for a singleton, but if you need a thread-safe, lazily-instantiated read-only property, maybe something like this will do the trick:
@implementation MyClass {
NSDictionary *_someDictionary
}
- (NSDictionary *) someDictionary {
@synchronized(self) {
if (!_someDictionary) {
_someDictionary = [[NSDictionary alloc] initWith… ]
}
}
return _someDictionary;
}
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden