Occasionally I want to perform code once in the lifetime of an object. In the past I’ve set up a BOOL property that I can check for, but that’s a little awkward. Is there something built-into Objective-C that elegantly accomplishes this? Somewhat like dispatch_once, but tied to the object rather than the lifetime of the application.
Occasionally I want to perform code once in the lifetime of an object. In
Share
You could use a dispatch_once_t instance variable to do this. Just beware subtle threading issues (not specific to dispatch_once) if you’re going to be using this object on multiple threads. You need a memory barrier at the end of init to be sure that the initialization of the ivar has completed before the object is visible to multiple threads.