iOS Singletons and Memory Management

后端 未结 2 1510
清酒与你
清酒与你 2021-02-03 12:27

I\'m certain that I\'m missing some fundamental understanding of iOS memory management and, despite lots of reading and searching, I\'m still not getting it.

I use a sin

相关标签:
2条回答
  • 2021-02-03 13:16

    Don't use singletons. Your current problem is caused by a simple memory management misconception, but the singleton pattern will only give you more headache in the long run.

    0 讨论(0)
  • 2021-02-03 13:27

    Your problem is:

    I get and set their values in methods in the singleton like this:

    myString = @"value";

    When you assign directly to the iVar, instead of using the property syntax (self.myString = @"value"), you are bypassing the synthesized setter method, which means that the retain never happens.

    Properties aren't magic. They're just a bit of syntactic sugar for the "." access, and the ability to have synthesized getter/setter methods to save you the tedium of writing your own.

    self.myString = @"value";
    

    is just shorthand for

    [self setMyString:@"value"];
    

    The synthesized setMyString method will do something like:

    if (myString != newValue) {
        [myString release];
        myString = [newValue retain];
    }
    

    (assuming retain option on the @synthesize)

    0 讨论(0)
提交回复
热议问题