Understanding when to call retain on an object?

前端 未结 4 442
礼貌的吻别
礼貌的吻别 2021-01-12 21:01

When should retain be used ? I understand that it increments the object references count, so basicly the next release on that object will not call

4条回答
  •  执笔经年
    2021-01-12 21:59

    All your answers are found in the Memory Management Guide.

    EDIT

    Following your edit, here's a bit more specific detail:

    in your code, you somewhere invoke a method a method that returns an object that you don't own

    Because you don't own it you have no control over it's lifetime. It could be released while you are still relying on it being a valid object.

    you work with that object

    Never sure that it is going to exist.

    then you want to release it => you can't because you're not the owner

    But why would you want to release it? You don't own the object so you aren't responsible for it's memory management.

    It looks as if you want to call release because you think that is how you manage memory, and that the retain is what let's you call it.

    Here is the way it should work:

    • You invoke a method that returns an object. If you haven't received this object by callingalloc, new, copy or mutableCopy then accoriding to the Memory Management Guide you don't own the object, so you aren't responsible for managing this memory.
    • In most cases you can assume that you have been passed an autoreleased object. That means that you have no control over it's lifetime. To make sure that it doesn't get released before you are done with it, you call retain on the object. You now own this object and are responsible for calling release on it at some time in the future. It is a beginner's mistake to now be concerned about the retain count on the object. Don't be. All that matters is that you are responsible for calling release on it.
    • You use the object keeping in mind the general memory management paradigm. For example, if you add this object to an NSArray then it will be retained by the array.
    • Once have have done what you need to do with the object, you call release on it. Again. Don't concern yourself with the object's retain count, or what other objects are using this object. All that matters is that you have balanced your calls to retain with an equal number of calls to release.

提交回复
热议问题