Arc Memory Management for iOS learning noteswrite in front
ARC (Automatic Reference counting), automatic reference counting, is a memory management method used in iOS.
pointer variables and object ownership
A pointer variable implies ownership of the object it points to
int Main ( int argc, const char * argv[]) { @autoreleasepool {//Insert code here ... nsstring *test = [[nsstring alloc] init]; } return 0 ;}
In the code above, there is a test object in the main function that points to nsstring, so the main function has the corresponding NSString object.
@interface item : nsobject {nsstring *_itemname;} @end
In the above code, we declare an item class that creates an instance variable of type NSString in its header file _itemname, so an object of item type has a NSString object.
Object ownership is used to help us decide whether to dispose of an object and reclaim the memory that the object occupies
-
If an object has no owner, it should be freed. An object without an owner is orphaned and the program cannot send a message to it. Preserving such objects only wastes valuable memory space, causing a memory leak issue.
-
If an object has one or more owners, it must be persisted and cannot be freed. If an object is disposed, but another object or method still has a pointer to the object (to be precise, the address before the object is freed), sending a message to the object pointed to by the pointer causes the app to crash. The error of releasing the object being used is called premature release. A pointer to an object that does not exist is called a null pointer or a null reference.
The case where the object loses its owner
-
When a program modifies a variable that points to a specific object and points it to another object.
-
When a program sets a variable that points to a specific object to nil.
-
When a program releases an owner of an object.
-
When an object is deleted from the collection class (for example, an array).
Ownership chain
Because an object can have other objects, which can also have other objects, releasing an object can have a ripple effect, causing multiple objects to lose their owner, freeing the object and returning the memory.
strong references and weak references
Strong Reference : If the pointer variable points to an object, then the corresponding object is one more owner and will not be released by the program, which is called a strong reference.
Weak references : Pointer variables do not affect the number of owners to which they point to an object. This pointer property, which does not change the number of object owners, is called a weak reference.
Weak references are ideal for resolving memory management issues with strong reference loops. A strong reference loop occurs when two or more two objects are associated with a pointer that has a strong reference attribute to one another. A strong reference loop can cause a memory leak. When two objects are owned by one another, they cannot be freed through the arc mechanism. Even if other objects in your app release ownership of both objects, both objects and their owning objects cannot be freed.
Attribute Properties
Attributes in iOS can be followed by a set of attributes that describe the behavior of the corresponding access method. These attributes are written in parentheses after the @property instruction. Such as:
@property (nonatomicreadwritecopyNSString *itemName;
where the first attribute is used to describe the multithreaded nature of a property, the second attribute is used to describe the read/write attribute of the property, and the third attribute is used to describe the property's memory management characteristics.
the memory management attribute of the property has four types of optional: strong、weak、copy and unsafe_unretained .
unsafe_unretained
for properties that do not point to any object, such as int value, you do not need to do memory management, so you should choose unsafe_unretained, which means that the access method assigns a value directly to the instance variable. Unsafe (unsafe) in unsafe_unretained is relative to weak references. Unlike weak references, when a pointer to a unsafe_unretained type is destroyed, the pointer is not automatically set to nil, but instead becomes a null pointer and is therefore unsafe. However, when working with non-object properties, there is no problem with null pointers. Unsafe_unretained is the default memory management feature for non-object properties, not explicitly written out.
for properties that point to the OC object, there are four types that are possible, by default the strong type, but usually need to be explicitly written out (Apple may modify the default value).
Strong
in an ARC environment, an object cannot be destroyed as long as it has a strong pointer to it. Once the object does not have a pointer to the strong type pointing to it, the object should be destroyed. The reference count of an object is equal to the number of strong pointers to that object.
Weak
in an ARC environment, the weak pointer does not increase its reference count to the object. When the object it points to is destroyed, the weak pointer is automatically set to nil, avoiding the presence of a wild pointer (pointing to a pointer that does not have memory)
Copy
copy is slightly more complicated. Divided into shallow copy and deep copy.
Shallow Copy
also known as pointer Copy, copy and source object is the same object, the reference count of the source object plus 1, its essence is to add a pointer to the source object.
Deep Copy
The replica object and the source object are different two objects, the source object reference counter is unchanged, and the replica object counter is 1. Its essence is the creation of new objects.
in addition, copy and Mutablecopy
Copy
classes that can receive copy messages must comply with the Nscopying protocol. For non-container class objects of the system, copy is a shallow copy
for the system's container class, if it is an immutable container, copy is a shallow copyfor the system's container class, if it is a mutable container, copy is a deep copy, but it returns the immutable object .
mutablecopy
classes that can receive mutablecopy messages must comply with the Nsmutablecopying protocol. For all classes, mutablecopy are deep copies.
first look at the case code of the system non-container class:
NSString*STR0 = [NSStringstringWithFormat:@ "Test"];NSString*STR1 = [STR0Copy];NSString*STR2 = [Str0 mutablecopy];NSLog(@ "The address of STR0 is:%p", STR0);NSLog(@ "The address of STR1 is:%p", str1);NSLog(@ "The address of STR2 is:%p", str2);
The results of the operation are as follows:
The str1 with copy can be seen with the same address as STR0, while STR2 generated with mutablecopy differs from the previous address.
Here is a case of a nsarray type
intMainintargcConst Char* argv[]) {@autoreleasepool{//Insert code here ... //Declare an immutable group and initialize Nsarray*array0 = [NsarrayArraywithobjects:@ "One",@ "both",Nil];//Copy a nsarray copy with copy, shallow copy Nsarray*array1 = [Array0Copy];//Copy a nsarray copy with mutablecopy, deep copy Nsarray*array2 = [Array0 mutablecopy];//Copy a nsmutablearray copy with copy, shallow copy Nsmutablearray*array3 = [Array0Copy];//[array2 addobject:@ "Three"];//can be compiled, but run abnormally //Copy a nsmutablearray copy with mutablecopy, deep copy Nsmutablearray*array4 = [Array0 mutablecopy]; [Array4 AddObject:@ "three"];//Compile and run are available through NSLog(@ "The address of Array0 is:%p", array0);NSLog(@ "The address of Array1 is:%p", array1);NSLog(@ "The address of Array2 is:%p", array2);NSLog(@ "The address of Array3 is:%p", ARRAY3);NSLog(@ "The address of Array4 is:%p", Array4); }return 0;}
The operation results are as follows
It can be seen that the address of array2, array4 with Mutablecopy is different from the Array0 address, and the other copy gets the same address.
If you want to customize an object that has replication attributes, you must implement the Nscopying,nsmutablecopying protocol to implement the Copywithzone method and Mutablecopywithzone method of the protocol. The difference between a deep copy and a shallow copy is the realization of the Copywithzone method,
usage of various memory features
Strong: The default property, except for the OC object outside of Nsstring/block, is used
Weak: Various UI controls (not absolute, some controls also use strong)
copy: Copy creates an immutable copy (imutable), and mutablecopy creates a mutable copy (mutable)
Summary
For strong, weak and other keywords in the attribute attribute, there is also a corresponding local variable version. Adding __strong before a local variable declares a local variable of a strong reference attribute.
In addition, having an arc does not mean that the programmer does not have to manually manage the memory at all. ARC can only be referenced on OC objects, if it involves the underlying malloc () or free (), arc is useless and must be manually managed by the programmer. Also, for a pointer of type strong, the programmer is manually set to nil after it is no longer in use.
ARC Memory management for iOS learning notes