Question about factory method object lifetimes in Objective-C/Cocoa (to retain or not…)

前端 未结 4 1098
遇见更好的自我
遇见更好的自我 2021-01-03 11:38

From reading the memory management docs in the SDK, I gathered that factory methods (static constructor methods) would typically be retaining the object for me and adding it

4条回答
  •  梦毁少年i
    2021-01-03 11:59

    From reading the memory management docs in the SDK, I gathered that factory methods (static constructor methods) would typically be retaining the object for me and adding it to the autorelease pool?

    Yes, you don't have to worry about releasing objects returned from any method, except the alloc, init, new, and copy methods.

    This would mean I have no need to retain & release an object as long as the pool does not get released before I expect?

    Yes.

    (Which should be at the end of the app, for the default autorelease pool in main()? )

    No. You can only count on the object being around until you return from whichever method or function you're in. Typically, autorelease pools are flushed when control returns back to your run loop.

    If you want an object instance to survive beyond the current method you must take ownership of it, by calling 'retain'. You are then also responsible for 'releasing' the instance when you no longer need it.

    In your case, if you want your NSMutableArray to stick around, you need to retain it. Better yet, use [[NSMutableArray alloc] initWithCapacity: ];

    See Practical Memory Management

提交回复
热议问题