iOS Memory Management Retain,assign,copy,strong,weak

Source: Internet
Author: User

Transferred from: http://www.cnblogs.com/nonato/archive/2013/11/28/3447162.html

iOS objects are inherited from NSObject, which has a method: Retaincount, memory reference count.

Reference counting is used in many techniques: COM components under window, multi-threaded semaphores, read and write locks, and thought alike.


(General: Exceptions are discussed later)
Alloc object is assigned a reference count of 1
Reference count for retain objects +1
Copy copy of an object into a new object (new memory address) reference count of 1 original object count unchanged

Release object reference count-1 if 0 frees memory
Autorelease object reference count-1 if 0 is not released immediately, released at the nearest pool
NSLog (@ "smessage retaincount:%u", [smessage Retaincount]);

The principle of memory management is to balance the final reference count,
Memory leaks If last reference count is greater than 0
If the reference count equals 0 also operates on the object, memory access failure occurs, crash so try to set as nil
Both of these problems are serious, so be sure to pay attention to memory release and set to nil after use



member variables and properties
It's not as simple as it is, you might need to call another function to assign a variable in one function.
There are two choices: class member variables and usage properties
@interface Testmem:nsobject {
Testobject *m_testobject; Member variables
Testobject *testobject; Member variables
}
The member variables are consistent with the memory management above, but the balance of reference count plus and minus is maintained in different functions.
So you have to check each time you assign the last time you've been assigned. Is it possible to invoke
When do I use attributes?
1. Make the members public.
2. Outlet is generally declared as a property (this memory is in the system control, but we should still do the same operation, will speak later)
3. If many functions need to change this object, or the function triggers many times, it is recommended to use attributes. Let's see what it looks like when the property function expands:

Assign
-(void) Settestobject:(ID) newvalue{
Testobject= NewValue;
}
Retain
-(void) Settestobject:(ID) newvalue{
if (testobject!= newvalue) {
[Testobject release];
testobject= [newvalue retain];
}
}
Copy
-(void) Settestobject:(ID) newvalue{
if (testobject! = newvalue) {
[Testobject release];
Testobject = [newvalue copy];
}
}
Asssign relative to the pointer assignment, do not operate the reference count, note that the original object is not necessary, be sure to set this to nil
Retain equivalent to the reference count of the original object plus 1
Copy does not change the reference count of the original object, generating a new object reference count of 1
Attention:
The Settestobject method is called by the Self.testobject Lvalue. The right value is the Get method, and the Get method is relatively simple.
Instead, the Testobject uses a member variable
Self.testobject = [[Testobject alloc] init]; Wrong Reatin two times
Testobject = [Nsarray objectbyindex:0]; It's not safe, there's no retain back, release will go wrong.
If Testobject already has a value, it will be mem leak



Automatically manage objects
IOS provides a lot of static (+) class methods for creating objects, which are statically, and can be directly used with the class name
Calls such as:
NSString *teststring = [nsstring stringwithformat:@ "test"];
TestString is an automatically managed object, you don't have to relese him, he has a big retain count, and the number does not change after release.

Exception
Some of the objects generated by Alloc are automatically managed as follows:
NSString *teststring = [[NSString alloc] initwithstring:@ "test1"];
Retain count is also a large number, no way to release
But for the code to correspond, still should add [teststring release];
Otherwise Xcode's analyze will recognize the memory leak, but instruments leak tool detection is not





The difference between copy and retain
Copy: Create an object with an index count of 1 and then release the old object
Retain: Frees the old object, assigns the value of the old object to the input object, and then increases the index count of the input object to 1
What the hell does that mean?
Copy actually creates an identical object, and retain is not:
such as a NSString object, the address is 0x1111, the content is @ "STR"
Copy to another nsstring, the address is 0x2222, the content is the same, the new object retain is 1, the old object has not changed
Retain to another nsstring, the same address (set up a pointer, pointer copy), the content of course the same, the object's retain value +1
That is, retain is a pointer copy and copy is a copy of the content. Wow, it's a lot easier than you think.

Mistakenly releasing objects
Question one:

1. Value = [array objectatindex:n]; To get an object in an array

2. [Arry removeobjectatindex:n]; Unload that object

Value = [array objectatindex:n]; To get an object in an array

[Arry Removeobjectatindex:n]; Unload that object





Because value gets that object, but because another owner release the object, the value is now a rocking pointer (invalid data)

Question two:

1. MyArray = [Nsarray array];

2 .....

3. [MyArray release];

MyArray = [Nsarray array]; ...

[MyArray release];

Nsarray returns an auto-release object, not only myarray should not be released after a period of time, but should be retain at the appropriate time to prevent the array from being mistakenly released by the system.

Question three:

1. Rocket = [Rocketlauncher arocket];

2. [Rocketlauncher release];

Rocket = [Rocketlauncher arocket];

[Rocketlauncher release];





Like array data-collection class objects, if we get a subclass of a class without retain it, the rocket actually loses its meaning when the original parent class is released.

Cocoa Autorelease in different memory management environments
H Mixed Memory Management Environment: garbage collection Method (garbage Collection) + Index counting method (Reference counting)
While in most cases a mixed environment is not recommended, if in this case autorelease need to be aware of the following:
Garbage collection mixed environment: the drain method should be used because release has no meaning in GC mode
Index count Environment: Drain and release have the same effect for Autoreleasepool (auto-free pool)

The misunderstanding of Autorelease
The memory management of a cocoa is divided into the index count method (Reference Counting/retain count) and the garbage collection method (garbage Collection). The iphone only supports the former, so Autorelease has become a "shortcut" for many people.
But! Autorelease is not actually "automatically released", unlike garbage collection, the relationship between objects detected after detection of garbage-delete. But Autorelease is actually "delayed release", which is marked as autorelease after a running cycle and is released.
Remember to use autorelease carefully, understand autorelease, and prevent it from being released by the system when you still need the object.

Memory management issues with Interface Builder involvement
Points:
If a variable is defined in the class in order to Iboutlet then you do not need to instantiate it, the xib loader initializes it.
If a variable is defined in the class in order to Iboutlet then you have to be responsible for releasing it. Xib loader will not help ...
* Do not initialize two back, memory will overflow, and object lock will be error.

Questions about index count (Reference counting)

1. *retain value = Index count//(Reference counting)



The Nsarray object retain the object in any array (retain value plus one). When Nsarray is unloaded (Dealloc), all objects in the array are freed once (the retain value is reduced by one). Not only Nsarray, but any collection class (Collection Classes) performs a similar operation. such as nsdictionary, or even uinavigationcontroller.
Alloc/init the object that is created, the index count is 1. No need to retain it again.
Methods such as [Nsarray array] and [NSDate Date] Establish an object with an index count of 1, but it is also an automatic release object. So it's a local temporary object, so it doesn't matter. If you are a variable (IVAR) that you intend to use in a full class, you must retain it.
The default class method return value is executed with the "auto-release" method. (* Nsarray in the above)
In the Unload method "Dealloc" in the class, release all the NS objects that are not balanced. (* All not autorelease, while retain value is 1)

NSString Memory Management
The following example:

1. astring = @ "I am a string, 2 years old, man!";



In this case, the string is stored and managed by the system, and we don't have to worry about it.

astring = [NSString stringwithformat:@ "I am a string,%d years old, man!", 2];



In the second case, we need to go to retain and release this string, regardless of the system.

OBJECTIVE-C Memory Management
You initialize (Alloc/init) The object and you need to release it (release). For example:

Nsmutablearray Aarray = [[Nsarray alloc] init];

[Aarray release];



2, you retain or copy the, you need to release it. For example:

[Aarray retain]

After the need

[Aarray release];



3, the object that is passed (assign), you need to consider the retain and release. For example:

Obj2 = [[Obj1 somemethod] autorelease];





Object 2 receives an automatically freed value of object 1, or passes a base data type (nsinteger,nsstring): You or you want to retain object 2 to prevent it from being automatically freed before it is used. But after retain, be sure to release it at the right time.

Why can't I just call dealloc instead of release?
Dealloc not equal to Free,dealloc in C does not release memory, nor does it degrade the index count (Reference counting). So the direct call to Dealloc instead of freeing memory.
In Objective-c, the index count plays a decisive role.





Strong and weak

Settings for properties in IOS 5 new strong and weak keywords to decorate properties (arc not supported before iOS 5)

Strong is used to modify properties of strong references;

@property (Strong) SomeClass * aobject;

corresponding to the original
@property (Retain) SomeClass * aobject; and @property (copy) SomeClass * aobject;

Weak is used to modify the properties of weak references;
@property (weak) SomeClass * aobject;
corresponding to the original

@property (assign) SomeClass * aobject;

iOS Memory Management Retain,assign,copy,strong,weak

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.