NSString @property, using copy instead of retain

前端 未结 3 1322
梦谈多话
梦谈多话 2020-12-05 03:09

I\'m looking over Apple\'s sample application EditableDetailView, and noticed that in one of their controllers, they\'re setting an instance of NSString property with (nonat

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 03:43

    (For some reason, this post is appearing above the follow-up question I am trying to answer) Re:

    did you mean that i have to copy 'the foo' object before releasing 'foo'??but whats the problem if i relaese 'foo' before copying 'the foo'??because they are two different object i can't understand why releasing one affect other!!!!

    Most of the time, you are correct. If they are, in fact, two separate objects, it won't matter. The problem lies in the possibility that you are assigning the same object back into itself. If you were to say

    [myObject setFoo: moof];
    [myObject setFoo: moof];
    

    Then the second time you did it, you would release moof before you copied it. In the intervening moment, it is possible that if moof's retain count went to zero then moof would be deleted, and you would have nothing to copy in the following step. Foo would now be nil.

    Is this likely to happen? Probably more than you might think. There are certainly times when the user might click on an "update" button twice, for example.

    I hope this is understandable and helpful.

提交回复
热议问题