读过 iOS Programming
All Objective-C objects are stored in a part of memory called the heap. When we send an alloc message to a class, a chunk of memory is allocated from the heap.
This chunk includes space for the object’s instance variables.
Pointer variables convery ownership of the objects that they point to.
1. When a method (or function) has a local variable that points to an object, that method is said to own the object being pointed to.
2. When an object has an instance variable that points to another object, the object with the pointer is said to own the object being pointed to.
The idea of object ownership helps us determine whether an object should be destroyed.
1. An object with no owners should be destroyed. An ownerless object cannot be sent messages and is isolated and useless to the application. Keeping it around
wastes precious memory. This is called a memory leak.
2. An object with at least one owner must not be destroyed. If an object is destroyed but another object or method still has a pointer to it (or, more accurately, a
pointer to where it used to live), then you have a very dangerous situation: sending a message to an object that no longer exists will crash your application.
This is called premature deallocation.引自第51页
How objects lose owners
1. A variable that points to the object is changed to point to another object.
2. A variable that points to the object is set to nil.
3. A variable that points to the object is itself destroyed.
A pointer variable stores the address of an object, that object has an owner and will stay alive. This is known as a strong reference.
However, a variable can optionally not take ownership of an object it points to. A variable that does not take ownership of an object is known as a weak reference.
A weak reference is useful for an unusual situation called a retain cycle. A retain cycle occurs when two or more objects have strong references to each other. This is bad news.
When two objects own each other, they will never be destroyed by ARC. Even if every other object in the application releases ownership of these objects, these objects (and any objects that they own) will continue to exist by virtue of those two strong references.
To declare a variable as a weak reference, we use the __weak attribute. In BNRItem.h, change the container instance variable to be a weak reference.引自第51页__weak BNRItem *container;Build and run the application again. This time, the objects are destroyed properly.
Every retain cycle can be broken down into a parent-child relationship. A parent typically keeps a strong reference to its child, so if a child needs a pointer to its
parent, that pointer must be a weak reference to avoid a retain cycle.引自第51页
__weak BNRItem *container;
A property is declared in the interface of a class where methods are declared. A proper...
Delegation is an object-oriented approach to callbacks. A callback is a function that i...