Setting property to newly alloc'd object using accessor cause memory leak

I just want confirmation on whether or not the following causes a memory leak.

.h file

  • Returning objects from methods in Objective-C
  • Set to nil in viewDidUnload, but release in dealloc
  • Does @“some text” give an autoreleased or retain 1 object back?
  • What is CG Raster Data?
  • How can I address an app that started earlier, but is “Terminated due to Memory Pressure” now?
  • Problems with memory management, autorelease, permanent heap is sometimes 250+ kb on iOS
  • @property (nonatomic, retain) MyObject *foo;
    

    .m file

    @synthesize foo;
    ...
    
    self.foo = [[MyObject alloc] init];
    

    dealloc is setup as

    [foo release];
    

    My understanding is that the implementation of the auto-generated accessor method looks like

    -(void)setFoo:(MyObject *)newObject {
        if (foo != newObject) {
            [foo release];
            foo = [newObject retain];
        }
    }
    

    Walking through self.foo = [[MyObject alloc] init]; now reads to me as, “allocated a new MyObject object whose retain count will be 1, pass it to setFoo:, foo will never be equal to myObject as it was newly allocated, so release the old value, increment the retain count of newObject making it 2 and assign it to foo”

    dealloc releases foo therefore setting its retain count to 1, which means this object is leaked?

    To do this safely we should write our code like

    self.foo = [[[MyObject alloc] init] autorelease];
    

    Is my understanding correct?

    EDIT

    I realize this question is not really appropriate for SO, so feel free to point me to a better place to ask this type of question as well.

    3 Solutions Collect From Internet About “Setting property to newly alloc'd object using accessor cause memory leak”

    Yes, that is absolutely correct.

    you could do that. Alternatively, since we know the setter automatically retains, we could do the following rather than autorelease:

    foo=[[MyObject alloc] init];
    

    Which you choose may be a matter of coding style. If you are trying to get the hang of using self.foo, then by all means use your method for the sake of consistency and bug fixing. If you are comfortable with using the dot syntax then use the latter.

    And another common pattern:

    MyObject *newFoo = [[MyObject alloc] init];
    self.foo = newFoo;
    [newFoo release];