0 x00 stack

  • Heap: allocated and managed by the program monkey, storing OC objects, for example, inherited fromNSObjectAll of these objects are reference types.
  • Stack: Managed by the system. Storage, such asint.floatAll of these objects are value types. The stack will be relatively efficient.

0x01 Object allocation and release

Memory Management mode

Apple provides two types of memory management:

  1. Manual retained release (MRR) : Manual retained release. Typically used in a runtime environment.
  2. ARC(Automatic Reference Counting) : Automatic Reference Counting. Used at compile time. With ARC, memory management is relegated to the system, and we only care about the implementation of objects, not the release of objects. (Care is not needed in basic cases).

Memory Management Principles

  1. You own the objects you own: through usealloc.new.copyormutableCopyMethods such as named methods create objects likestringWithFormat:Objects created by such methods cannot be held
  2. useretainTo obtain the ownership of the object:retainThere are two usage scenarios: 1) method implementation in accessor orinitMethod to obtain the desired object and use it as an attribute value 2) to avoid the impact of other operations on the object
  3. After the object is not used, it must be discarded: sendreleaseorautoreleaseMessage to the object
  4. Can’t free objects that you don’t own!

releaseandautorelease

Sending a release message immediately frees the object. If you want to delay releasing an object, you can use AutoRelease.

Objects returned by reference are not held.

usedeallocTo discard the possession of the object

One thing to note here is that you cannot call the dealloc method of another object directly

Don’t beinitordeallocAccessor methods are used in the

Apple’s official documentation says not to use Accessor Methods in initialization or release Methods (this is probably in the MRC phase, apple’s memory management documentation is a bit older, but this is a personal understanding that needs to be verified). So in the initialization method, it should look like this:

- (instancetype)init {
  self = [super init];
  if (self) {
    _count = [[NSNumber alloc] initWithInteger: 0];
  }
  return self;
}
Copy the code

Core Foundation

For normal OC objects, you only need to use ARC to count for memory management. For the underlying Core Foundation, the CFRetain() and CFRelease() methods are called to increase or decrease the reference count.

OC objects and Core Foundation objects are converted using the Bridge keyword.

  • __bridge: Performs only type conversions without modifying reference counts
  • __bridge_retained: The reference count increases by 1 after a type conversion
  • __bridge_transferAfter the type conversion, the reference count of the object is managed by ARC

weak

Weak references are a non-owning relationship, so objects are not retained.

A variable declared weak prevents memory problems caused by circular references, because objects are set to nil if they don’t have strong references. This should be distinguished from unsafe_unretained. Unsafe_unretained objects don’t get nil if they don’t have strong references. If the object is reclaimed or destroyed, the pointer becomes a wild pointer.

Retain an object creates a strong reference to that object.

Circular reference resolution

One way around circular references is to use weak references. As you can see in the figure, Cocoa has a convention that a parent object is a strong reference to its child, and a child object is a weak reference to its parent. In the example above, the Page object strongly references the Paragraph, and the Paragraph weakly references the Page.

If you send a message to something that’s already been released, it’s going to crash, as opposed to sending a message to nil. OC is allowed to send messages to nil.

The collection type retains the objects it contains

Collection objects such as Array, Dictionary, and Set retain their object. The object will only be removed when the collection object is removed or released.

0x02 Wild pointer error

Thread 1: EXC_BAD_ACCESS(code=EXC_I386_GPFIT) error The reason is to access a piece of memory that has been freed or does not belong to you.

0x03 Retained/Unretained return value

  • Retained return value: The caller owns the return value and is responsible for releasing it. For example,alloc.copy.init.mutableCopyandnewThe way to start
  • Unretained return value: The caller does not own this return value. Such as[NSString stringWithFormat:]This approach

0x04 Memory Leaks

There are two types of memory leaks:

  • Leaked memory: Memory unreferenced by your application that cannot be used again or freed (also detectable by using the Leaks instrument).
  • Abandoned memory: Memory still referenced by your application that has no useful purpose.

The first of these can be detected using the Leak tool, and the second using Allocations

0x05 Block allocation and release

Blocks are initially released on the stack, but at run time the Block_copy method is called to copy the Block object to the heap, increment the reference count by one, and return a new Block pointer (if the Block object already exists in the heap, increment the reference count by one). The Block_release method subtracts the reference count by one, or releases and destroys the object when the count reaches zero.

#0x08 Autorelease Pool Block

@autoreleasepool {
  // Code
}
Copy the code

Autoreleasepool is typically used in three situations:

  1. For example, programs like command line tools that are not based on the UI framework
  2. You create a lot of temporary objects in your own loop
  3. Generate helper threads: in this case you must create your own while the thread is executingautoreleasepoolBlock, otherwise causing a memory leak

0x07 Other

  1. In general,allocandreleaseSupporting the use

See article portal

  1. Memory allocation in Objective-C