Objective C: Memory Allocation on stack vs. heap

前端 未结 4 1391
误落风尘
误落风尘 2020-12-08 08:28

I am somewhat confused about when things are allocated on the heap (and I need to release them) and when they are allocated on the stack (and I don\'t need to relese them).

相关标签:
4条回答
  • 2020-12-08 08:33

    There are no stack allocations of objects in Objective-C (Blocks are a different case that I'm not going to get into here)

    NSString *user = @"DEFAULT";
    

    That allocates a NSConstantString object in constant memory, not on the stack.

    0 讨论(0)
  • 2020-12-08 08:43

    In Objective-C (and many other languages), an object is simply a contiguous blob of memory with a particular layout. Objects are usually created on the heap. The storage for the object pointer variable itself is on the stack but the object it points to is in the heap.

    0 讨论(0)
  • 2020-12-08 08:45

    Objective-C is easy in this regard.

    All Objective-C Objects Are Always Allocated On The Heap.

    Or, at the least, should be treated as if they are on the heap.

    For:

    NSString *user = @"DEFAULT";
    

    The string object is not technically in the heap, but might as well be. Namely, it is generated by the compiler and is a part of your app's binary. It doesn't need to be retained and released because the class (NSCFConstantString, IIRC) overrides retain/release/autorelease to effectively do nothing.

    As for when you do and don't release objects, you should read (and re-read) the Objective-C memory management guide.

    (There is one other exception, but it is a rather esoteric detail; blocks start on the stack and you can Block_copy() them to the heap. Blocks also happen to be Objective-C objects, but that is rarely exposed in use.)

    0 讨论(0)
  • 2020-12-08 08:53

    In Objective-C, it's easy: all objects are allocated on the heap.

    The rule is, if you call a method with alloc or new or copy in the name (or you call retain), you own that object, and you must release it at some point later when you are done with it. There has been plenty written on the subject.

    The example you give is a special case: that's a static string, I believe it is actually located in the program's data segment (on the heap), but it's static so you don't need to worry about releasing it.

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