thread safety - How to implement lazy evaluation of objective-C property which may be nil? -
in objective-c, how can implement lazy evaluation of property may nil?
the usual practice demonstrated below, not work properties may nil - initialization won't performed once.
@interface lzclass: nsobject @property (strong, readonly) nsstring * lazyprop; @end @implementation lzclass @synthesize lazyprop = _lazyprop; - (nsstring *)lazyprop { if (_lazyprop == nil) { _lazyprop = <some calculation>; } return _lazyprop } @end
update: answer isn't safe. see yan's comment below. leaving here people have same idea can beware.
use dispatch_once
instead of checking nil.
@interface lzclass: nsobject { dispatch_once_t _oncetoken; } @property (strong, readonly) nsstring * lazyprop; @end @implementation lzclass @synthesize lazyprop = _lazyprop; - (nsstring *)lazyprop { dispatch_once(&_oncetoken, ^{ _lazyprop = <some calculation>; } return _lazyprop } @end
this has advantage of being thread-safe. threads trying read property while initialization block being executed block, , continue after initialization block returns. therefore correct result guaranteed returned in threads.
also beware: standard code snippet dispatch_once
defines static oncetoken
, won't work correctly here; initialization block executed first object of class.
Comments
Post a Comment