Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6723055
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T09:31:22+00:00 2026-05-26T09:31:22+00:00

I have a view controller that I want to lazily initialize, and once initialized,

  • 0

I have a view controller that I want to lazily initialize, and once initialized, use the same copy when possible (I don’t use a singleton since I do want to remove it from memory eventually), I use the getter to do so, my code look like this:

@property (retain) UIViewController *myController

...

@synthesize myController = _myController;


...


- (UIViewController *)myController
{
    if (!_myController) {                                 // Evaluation
        _myController = [[MyViewController alloc] init];  // Object Creation
    }
    return _myController;
}

This works, but it’s not thread safe, and if more than one thread evaluate to true before the object is created, I’ll have a memory leak. One solution I’ve tried is to @synchronized the code, but I’m not sure the correct way to do it.

This appears to work, (lockForMyController is a simple NSString) but it makes this section of code a lot slower:

 - (UIViewController *)myController
{
    @synchronized(self.lockForMyController){
        if (!_myController) {
            _myController = [[MyViewController alloc] init];
        }
    }
    return _myController;
}

I was wondering if there is some other way to achieve a lazy initialized, thread safe, property?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T09:31:22+00:00Added an answer on May 26, 2026 at 9:31 am

    This solution works

    Note that this solution only works if myController is accessed on a background thread the first time. It will deadlock if called on the main thread.

    You want to use gcd. The key is serialize the creation of the object, so that regardless of the threads starting the block, it will always only be created exactly once.

    - (UIViewController *)myController
        if (_myController == nil) {
            dispatch_sync(dispatch_get_main_queue(), ^ { if (_myController == nil) _myController = [[MyViewController alloc] init]; });
        }
        return _myController;
    }
    

    Here, even if multiple threads execute the block, the execution of the block is serialized onto the main thread and only one MyViewController can ever be created.

    You won’t see a performance hit here unless the object is nil.

    Since the property is implicitly atomic, that means that in the setter the value will be autoreleased. This should make it suitable for mingling with your custom getting, since it will autorelease any value changes to _myController.

    http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW2

    However, you still may get into a race condition where you are setting the value on one thread but accessing it on another. Any time you set the value, you probably want to make sure and do something like this:

    dispatch_sync(dispatch_get_main_queue(), ^ { self.myController = {newValueOrNil} });

    This will make sure to serialize your setter methods calls without having to reinvent the wheel for atomic setters, which is very hard to get right.

    This solution does not work

    You want to use gcd.

    http://developer.apple.com/library/ios/documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html#//apple_ref/c/func/dispatch_once

    See this post about singletons. I know you don’t want a singleton, but this demonstrates how to use the method. You can easily adapt it.

    Create singleton using GCD's dispatch_once in Objective C

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have several types os root view controller that I want to instantiate one
If I have a custom view controller class that I want to reuse but
I have a view controller that I want to be released (and then possibly
I have a view controller that is inside a popover, and I want to
I have a view controller that gets presented modally and changes some data that
In a word, how? I have a view controller that creates a few custom
I have a view controller class that has to implement several protocols. Too keep
I have a few methods inside my view controller that load up for future
I have the problem that my view controller class has too many delegates and
I have a Java project that I'm trying to implement with a model-view-controller design.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.