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 1088363
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T23:03:42+00:00 2026-05-16T23:03:42+00:00

This is a small detail but everytime I lazy load something I get caught

  • 0

This is a small detail but everytime I lazy load something I get caught up on it. Are both of these methods acceptable? Is either better? Assume that the variable has the retain property.

Method #1

(AnObject *)theObject{
    if (theObject == nil){
        theObject = [[AnObject createAnAutoreleasedObject] retain];
    }
    return theObject;
}

Method #2

(AnObject *)theObject{
    if (theObject == nil){
        self.theObject = [AnObject createAnAutoreleasedObject];
    }
    return theObject;
}

First, I’m not sure if it’s OK to access another accessor function within an accessor (don’t see why not, though). But it seems like setting the class variable without going through the setter could be equally bad if the setter does something special (or if the property is changed to something besides retain and the getter isn’t checked).

  • 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-16T23:03:42+00:00Added an answer on May 16, 2026 at 11:03 pm

    Both are actually quite fragile and not at all identical, depending on what clients of the class are doing. Making them identical is easy enough — see below — but making it less fragile is harder. Such is the price of lazy initialization (and why I generally try to avoid lazy initialization in this fashion, preferring to treat initialization of subsystems as a part of overall application state management).

    With #1, you are avoiding the setter and, thus, anything observing the change won’t see the change. By “observing”, I’m specifically referring to key-value observation (including Cocoa Bindings, which uses KVO to update the UI automatically).

    With #2, you will trigger the change notification, updating the UI and otherwise exactly as if the setter was called.

    In both cases, you have a potential for infinite recursion if the initialization of the object calls the getter. That includes if any observer asks for the old value as a part of the change notification. Don’t do that.

    If you are going to use either method, consider carefully the consequences. One has the potential to leave the app in an inconsistent state because a state change of a property did not notify and the other has the potential for deadlock.

    Better to avoid the issue entirely. See below.


    Consider (garbage collection on, standard Cocoa command line tool:

    #import <Foundation/Foundation.h>
    
    @interface Foo : NSObject
    {
        NSString *bar;
    }
    @property(nonatomic, retain) NSString *bar;
    @end
    @implementation Foo
    - (NSString *) bar
    {
        if (!bar) {
            NSLog(@"[%@ %@] lazy setting", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
            [self willChangeValueForKey: @"bar"];
            bar = @"lazy value";
            [self didChangeValueForKey: @"bar"];
        }
        return bar;
    }
    
    - (void) setBar: (NSString *) aString
    {
        NSLog(@"[%@ %@] setting value %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), aString);
        bar = aString;
    }
    @end
    
    @interface Bar:NSObject
    @end
    @implementation Bar
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context;
    {
        NSLog(@"[%@ %@] %@ changed\n\tchange:%@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), keyPath, change);
    }
    @end
    
    int main (int argc, const char * argv[]) {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
        Foo *foo = [Foo new];
        Bar *observer = [Bar new];
        CFRetain(observer);
        [foo addObserver:observer forKeyPath:@"bar"
                 options: NSKeyValueObservingOptionPrior | NSKeyValueObservingOptionNew
                 context:NULL];
        foo.bar;
        foo.bar = @"baz";
        CFRelease(observer);
    
        [pool drain];
        return 0;
    }
    

    This does not hang. It spews:

    2010-09-15 12:29:18.377 foobar[27795:903] [Foo bar] lazy setting
    2010-09-15 12:29:18.396 foobar[27795:903] [Bar observeValueForKeyPath:ofObject:change:context:] bar changed
        change:{
        kind = 1;
        notificationIsPrior = 1;
    }
    2010-09-15 12:29:18.397 foobar[27795:903] [Bar observeValueForKeyPath:ofObject:change:context:] bar changed
        change:{
        kind = 1;
        new = "lazy value";
    }
    2010-09-15 12:29:18.400 foobar[27795:903] [Bar observeValueForKeyPath:ofObject:change:context:] bar changed
        change:{
        kind = 1;
        notificationIsPrior = 1;
    }
    2010-09-15 12:29:18.400 foobar[27795:903] [Foo setBar:] setting value baz
    2010-09-15 12:29:18.401 foobar[27795:903] [Bar observeValueForKeyPath:ofObject:change:context:] bar changed
        change:{
        kind = 1;
        new = baz;
    }
    

    If you were to add NSKeyValueObservingOptionOld to the list of options for observation, it very much does hang.

    Getting back to a comment I made earlier; the best solution is to not do lazy initialization as a part of your getter/setter. It is too fine grained. You are far better off managing your object graph state at a higher level and, as a part of that, have a state transition that is basically of the “Yo! I’m going to use this subsystem now! Warm that bad boy up!” that does the lazy initialization.

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

Sidebar

Related Questions

I have this small program and it needs to create a small .txt file
I'm learning ASP.NET MVC. I had a small problem when dealing with dropdownlist. This
A small number of our users are experiencing an error when they try to
I have a small set of css items in a db table that I
I'm writing an iPhone app that (like most apps) supports auto-rotation: You rotate your
I am looking for a simple XML editor to start learning XML and then
How can I tell jQuery to automatically use jsonp for cross-domain ajax requests while
I come from a python background, where it's often said that it's easier to
I have a profile card of user that have registration in my forum. Person.update_all({:name
I am running Celery 2.2.4/djCelery 2.2.4, using RabbitMQ 2.1.1 as a backend. I recently

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.