"iOS Dev-33" Learn manual memory management temporary discard arc and retain/assign Knowledge--iosproject interview must test content

Source: Internet
Author: User

Why do we need memory management? A warning is issued when memory reaches 40M and 45M, assuming it is not processed and the program is directly forced to shut down when the memory reaches 120M.

So the flash-out is a logic error in the program, and it is possible that memory usage is too large.


(1) The process of creating an object: allocating memory space to store objects, initializing member variables, and returning pointers to objects.


(2) When the object is created, the internal will create a reference counter itself Retaincount, when retaincount=0, the system reclaims the current object, Retaincount is the only inference token. Release will-1. Retain will return the self-pointer after +1,retain.


(3) Turn the arc off into manual memory management mode.



(4) Memory pairing principle: Only new, alloc, or retain need to be paired with a release or autorelease.

In main.m, @autorelease pool{} needs to be removed. Managed by hand:

#import <Foundation/Foundation.h> #import "Person.h" int main (int argc, const char * argv[]) {        // Alloc retaincount=1 person        *p1=[[person Alloc]init];        NSLog (@ "%lu", p1.retaincount);                Reference count =2        [P1 retain];        NSLog (@ "%lu", p1.retaincount);                Reference count =1        [P1 release];        NSLog (@ "%lu", p1.retaincount);                Reference count =0        [P1 release];        How do I verify that the object has been destroyed at this time? The Dealloc method is called when each object is destroyed, and we rewrite dealloc to let it output something. The proof is called can        //override is in the. m file of the class to which this object belongs, i.e. return 0 in the person.m of this example            ;

In the PERSON.M:

#import "Person.h" @implementation person-(void) dealloc{        //Before the object is destroyed, use the following statement to release the related object in the parent class    [Super Dealloc];    NSLog (@ "I am Dealloc");} @end

(5) After an object is recycled. This object is called a Zombie object, because Xcode does not always check the zombie object, so when the cmd+r execution, access to the object has been recycled sometimes error, sometimes do not error.

Suppose you want Xcode to always check. Settings below. Default is not always checked. is to improve coding efficiency.

But it is recommended to close. Because when the analogy is much larger, it consumes memory.




(6) The two problems of manual memory management research are: wild pointers and memory leaks. When the object is reclaimed and the pointer variable is not set to nil, the pointer is a wild pointer, which causes the program to flash back. So we usually set this pointer variable to nil after release. Although may also use P1, but P1 is nil. Send to it no matter what the message has no response and no impact, there will be no flash back.


(7) Memory leaks: The first case is that objects that are no longer being used are not recycled in memory. Another case is to accidentally set the pointer variable to nil first. And then [P1 release]; it is invalid because Retaincount is a unique tag, although there is no pointer pointing to the object, but the object still exists in memory.

#import <Foundation/Foundation.h> #import "Person.h" int main (int argc, const char * argv[]) {        // Alloc retaincount=1 person        *p1=[[person Alloc]init];        NSLog (@ "%lu", p1.retaincount);                Reference count =2        [P1 retain];        NSLog (@ "%lu", p1.retaincount);                Reference count =1        [P1 release];        NSLog (@ "%lu", p1.retaincount);                Reference count =0        [P1 release];        How do I verify that the object has been destroyed at this time? Each object is destroyed when the Dealloc method is called and we rewrite Dealloc. Let it output something. The proof is called and can be        overridden in the. m file of the class to which this object belongs. That is, the person.m in this example            return 0;}

(8) After defining a P1 pointer variable, assign it to a pointer variable P2. Then this object retaincount unchanged. Just one more P2 point to this object. No matter what a P1 and P2 are able to release this object. After release, these two pointer variables assume that they are not set to nil to become wild pointers.


(9) When a pointer variable is passed as a parameter to another method. It does not add a reference count that points to the object.

So in the final analysis whether there is no retain, new, alloc, and see if it is paired with release, Autorelease.


The Car class is a subclass of the person class, and there is a method for the man class-(void) Setcar: (Car *) Car{_car=car;} and-(void) Drive{[_car Run];},run method is the method of the car class. In the main function our person object P1 need to be paired with a release when Alloc. If you need to use [P1 Drive], then you need to instantiate a car object car1, then you need to match a release for Car1. Usually Car1 's alloc and release are wrapped in P1 's alloc and release.

Suppose I plan to [CAR1 release], and [P1 release], and then use P1 's Casual method, for example [P1 Drive], and find that CAR1 has been release, so it will be an error. In other words, my P1 object still exists. But I can't use it all the way I feel. How to solve?


The first step is to change the Setcar method to _car=[car retain], which is equivalent to retaincount+1 for this Car1 object. So even if we use the pairing principle in the main function. Retaincount still has 1. So p1 can be used freely.

The second step is to eliminate 1 of the car1 retaincount that still exist above. Our aim is to make this car1 retaincount always be 1. Unless my P1 is gone, the car1 can not be. So we need to eliminate it in the absence of P1, that is, in the P1 of the dealloc to eliminate it, the elimination is to put it [_car release];


(11) Answer the above question: assuming that the main function within the continuous definition of two car object variables car1 and Car2, the last object variable memory management is normal, but the previous few are not normal.

Since Car1 's retaincount is still 1. The _car inside the dealloc is car2, so car2 memory is normal, car1 is not normal, memory leaks. How to solve it?


The problem is to focus on setcar and add a sentence [_car release] in front of it; When the first call to _car is nil, it does not affect. After a round of Car1 Retaincount is 2, when the second call [_car release]; _car is car1, so Car1 is released, and then Car2 is turned into 2, The CAR2 is then released separately in the main function and Dealloc.


(12) Answer the above questions. Suppose I call Setcar a second time to pass CAR2, but still pass the time car1. Then at this time in the second call, encountered [_car release], then has released the CAR1, so the following sentence _car=[car retain]; it becomes a wild pointer operation. How to solve it?


We give this [_car release}; Add 1 inference statements. Because the assumption is that the same object has no new object passed in, _car is always the object. Then we will be in the Dealloc [_car release], release, and assume that the subsequent transfer of the object and the last time the difference, in Dealloc [_car release]; it becomes the second object is released, the first object is less a release operation.

So our conclusion is to infer that the new object being passed is the one that was last. It is not released in this, otherwise it is released here.

That is, if (_car!=car) {[_car release];_car=[car retain], the core of this sentence is release old value, retain new value.

and assume that the same object was passed as the last time. No matter what the operation, Retaincount is still 1.


(13) Therefore, summarize the memory management of the member variable object. is: a) primarily for setter methods. b) Add an if (new value) in the Setter Method!

= old value) {release old value, retain new value};c) and write a release in the Dealloc function of the class.


(14) In fact, when using @property to define member variables, the fact that different parameters are used in instructing the program to generate different types of setter methods. Retain is a setter method that instructs the program to generate memory management, which is the string above if. Assign is the common setter method, so we generally use retain for object types. The basic data type is used assign.

However, the key is that the above retain only changed the setter method, and did not voluntarily release in the Dealloc. So, while we're using @property (retain) * * * *, although we don't need to rewrite the setter method, we need to rewrite the Dealloc method of the class to release this member variable once.


(15) by the way, thread management parameters Atomic is the residue of the Mac development, generally iOS is nonatomic, and to write, because the default is atomic. So generally there are only two forms of @property (Nonatomic,retain) Char *char1; and @property (nonatomic,assign) int age;


(16) by the way, ReadWrite (Generate getter and setter methods) and readonly (just generate Getter method), default is ReadWrite.

The following statement can be used to replace the default setter or Getter Method name @property (nonatomic,assign,setter=abc) int age, and the subsequent call setter method is directly replaced with ABC.

This is generally used to change the name of the setter and getter when defining the bool variable, and is generally changed to isxxx.


"iOS Dev-33" Learn manual memory management temporary discard arc and retain/assign Knowledge--iosproject interview must test content

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.