IOS Memory Management (1)

Source: Internet
Author: User

Thinking about counting memory management:

  • The object generated by yourself.
  • You can also hold non-self-generated objects.
  • Release an object that you no longer need.
  • Objects not owned by the user cannot be released.

Object operations

Objective-C method

Generate and hold objects

Alloc/New/copy/mutablecopy Method

Owner

Retain Method

Release object

Release Method

Deprecated object

Dealloc Method

The nsobject class in the foundation framework in the cocoa framework is responsible for memory management. The alloc/retain/release/dealloc methods in memory management refer to the alloc class methods of the nsobject class and the retain instance methods respectively,

Release instance method and dealloc instance method.

 

1. Self-generated object, owned

The method name starting with the following name means that the object generated by the user is only owned by the user.

  • Alloc
  • New
  • Copy
  • Mutalecopy
First look at the first two: alloc new
// Use the alloc class method to generate and hold the object by yourself. the pointer pointing to the generated and holding object is assigned to the variable obj id obj = [[nsobject alloc] init]; // The new class method can also be used to generate and hold objects. Therefore, alloc and new are exactly the same id obj = [nsobject new];

Correct: The alloc and new statements mentioned in the code comment above are completely consistent. This statement is incorrect! The statement [nsobject new] and [[nsobject alloc] init] are used in the same way.
Next let's take a look at the last two copies mutablecopy
These two understandings are a bit complicated. The copy method uses the nscopying-Based Method convention to generate and hold copies of objects from various implementation copywithzone: methods.
Similar to the copy method, the mutablecopy method uses the nsmutablecopying method convention to generate and hold copies of objects in mutablecopywithzone.
The difference between the two is:
The copy method generates unchangeable objects, while the mutablecopy method generates changeable objects. (This may be a bit abstract. Here is an example !)

1. mutablecopy creates a new variable object and initializes it as the value of the original object. The reference count of the new object is 1;

2. Copy returns an unchangeable object. There are two situations:

(1) If the original object is an immutable object, return the original object and add the reference count to 1;

(2) If the original object is a mutable object, create a new immutable object and initialize it as the value of the original object. The reference count of the new object is 1.

// Create an unchangeable array nsarray * immutablearray = [[nsarray alloc] initwithobjects: @ "one", @ "two", @ "three", nil]; // nsmutablearray * mutablearray = [immutablearray mutablecopy]; [mutablearray addobject: @ "four"]; nslog (@ "Count = % lD ", (unsigned long) [mutablearray count]); // output: Count = 4 nsmutablearray * array = [[nsmutablearray alloc] init]; array = [mutablearray copy]; // note that copy is an immutable object, Although nsmutablearray is used. Therefore, the following statement adds an element to the array. Although the compilation is successful, an error occurs during running. [Array addobject: @ "five"]; // An error occurred while running

Further,Copy is a shallow copy, while mutablecopy is a deep copy.
Copying an object is to create a new instance and initialize it as the copy source value. For values such as Boolean and integer, copying is a direct assignment. Pointer objects are divided into shortest copy and deep copy. A shallow copy creates only one pointer and points to the same data block. Deep copy creates both data and pointers.

Question: I originally wanted to use the retaincount instance method to observe the reference count value, but I found a problem:

NSObject* obj = [[NSObject alloc] init];    NSLog(@"%li",(unsigned long)[obj retainCount]); // print: 1    [obj release];    NSLog(@"%li",(unsigned long)[obj retainCount]); // print: 1

This code is output 1 twice; the first output 1 should be OK, because alloc makes reference count + 1; then release, then reference count value-1, so we should output 0! Why?
The problem is as follows:
First, let's take a look at how the retaincount method is introduced in the document:

Do not use this method. (required)


This method is of no value in debugging memory management issues. Because any number of framework objects may have

Retained an object in order to hold references to it, while at the same time autorelease pools may be holding any number

Deferred releases on an object,
It is very unlikely that you can get useful information from this method.


This method has no value in the debugging process (You should not use it), because the system will delay the release of objects, therefore, it is unlikely that useful information can be obtained through this method.
So? The information obtained by the last statement output reference count value through retaincount is inaccurate. In fact, the object has been released, but the system has released the reference count value in a delayed manner. That is to say, when the last output statement is executed
In fact, the object OBJ has not been released (the reference count value is not 0). If it is equal to 0, isn't the system abandoning the object directly? Then how can you call the retaincount instance method.
You can test it like this. If you add a release statement, the program will crash, or do not use have a try! This is my understanding.

2. You can also hold non-self-generated objects.
Objects obtained using methods other than alloc new copy mutablecopy are not generated by the user. All objects are not owned by the user, but the existence of objects can be obtained.

// Obtain the object, but it does not own the Object id obj = [nsmutablearray array]; // you can use retain to hold the object [OBJ retain];

You can use the retain method to own non-self-generated objects, just as using the alloc new copy mutablecopy method to generate and hold objects.
3. release an object that you no longer need
If you do not need an object, the owner is obligated to release the object and use the release method.

Uilabel * label = [[uilabel alloc] initwithframe: cgrectmake (10, 10,100,100)]; [label release]; // The released object cannot be accessed. TEXT = @ "Hello World"; // will crash during runtime

4,
If you want to use a method to generate an object and return it to the caller of the method, how can this problem be achieved?

-(id)allocObject {    id obj = [[NSObject alloc]init];    return obj;}

Note that the method naming rules must start with alloc new copy mutablecopy.
So if you want to get the existence of an object through a method without holding the object, how can we implement it?

-(ID) object {id obj = [[nsobject alloc] init]; // The self-held object [OBJ autorelease]; // retrieves the object's existence, but you do not own the object return OBJ ;}


Note that the naming rules of methods should not start with alloc new copy mutablecopy because they do not hold objects.

The autorelease method is used above. You can use this method to obtain the existence of an object, but you do not own it. Autorelease provides this function to automatically and correctly release an object when it exceeds the specified survival range (call the release method ).

[OBJ autorelease]; this statement registers the OBJ object to autoreleasepool and automatically calls the release method when the pool ends. In this way, let autoreleasepool hold the object and let it take charge of the release of the object.


Method call

Id obj1 = [self allocobject]; // the Object ID obj2 = [self object] held by the user; // the object is not held by the user, only get the object existence // Of course, you can also use the retain method to hold this object [obj2 retain];


5. objects not owned by the user cannot be released.
For objects generated and held by the alloc new copy mutablecopy method, or objects held by the retain method, because the owner is the owner, the release object must be called when no object is needed, in addition, the obtained objects cannot be released. If an object is released in the program, it will cause a crash.

// Example 1 ID obj1 = [self allocobject]; // The object held by the user [obj1 release]; // the object has been released [obj1 release]; // when you release an object that is not owned by yourself, access the discarded object and the program crashes. // Example 2 ID obj2 = [self object]; // you do not own the object, only get the object [obj2 release]; // release the object that is not held by the user, and the program crashes.

The allocobject method and object method are the same as above.
6. Memory Management using reference count values:

  • There is a reference count in the objective-C object.
  • Call the retain or alloc new copy mutablecopy method to reference the Count value + 1;
  • After release is called, the reference count value is-1;
  • When the reference count is 0, call the dealloc method to discard the object.
7. autorelease
Autorelease is the feature of automatic release, which is similar to the feature of automatic variables (local variables) in C language.

In C language, if the automatic variable exceeds the scope during program execution, it is automatically discarded. Similarly, autorelease treats instance objects like automatic variables in C. When it exceeds the scope, the release method of the object instance is automatically called.
The usage is as follows:
NSAID utoreleasepool * Pool = [[NSAID utoreleasepool alloc] init]; // generate and hold the NSAID utoreleasepool Object id obj = [[nsobject alloc] init]; [OBJ autorelease]; // call the autorelease [pool drain] of the allocated object; // call the autoreleasepool object.

[Pool drain] of the last row; equivalent to [poolrelease];

This article also summarizes the excerpt from the book "objective-C advanced programming iOS and OS X multithreading and memory management. Start to learn about memory management. This is the first record.

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.