iOS Classic test Summary--memory management

Source: Internet
Author: User
Tags scalar

iOS Classic test Summary--memory management

Memory management

1. What is ARC?

ARC is the automatic reference counting automatic reference count, which is automatically added to the retain/release when the program is compiled. Retain count+1 when an object is created, count-1 when the object is release, destroying the object when count=0. Adding the Autoreleasepool object to the program is automatically added by the system to the Autorelease method and destroyed if the object reference count is 0. Then Arc was born to solve some of the MRC's Manual management of memory existence.

The drawbacks of memory management under MRC:

    • When releasing a heap of memory, first make sure that the pointer to this heap space is released. (Avoid early release)

    • Frees the heap space that the pointer points to, first to determine which points to the same heap, which can be released only once. (Avoid releasing multiple times, causing memory leaks)

    • When a module is in operation, the object may be created and used by multiple modules and cannot be determined by who is finally released

    • When you are multithreaded, you are not sure which thread was last used.

Although Arc gives us a lot of programming, there may be a memory leak. Here are two scenarios:

    • Circular reference: A has an attribute reference B,b has a property reference A, if all are strong references, two objects cannot be freed.

    • Dead loop: If there is an infinite loop in a viewcontroller, it also causes the Viewcontroller to be released even if the viewcontroller corresponding view disappears.

2.block is usually decorated with that keyword, why?

Block is typically modified using copy key, block using copy is the "legacy" from the MRC, in the MRC, the method content block is in the stack area, using copy can put it into the heap area. But it's OK to write in Arc: The compiler automatically copy the block.

3. NSString (or nsarray,nsdictionary) using the @property declaration often uses the Copy keyword, why? If you use the strong keyword, what might be causing the problem?

A: Using @property to declare NSString, Nsarray, and nsdictionary often use the Copy keyword because they have a corresponding mutable type: nsmutablestring, Nsmutablearray, Nsmutabledictionary, they may perform assignment operations to ensure that the string values in the object are not inadvertently changed, and that a copy should be made when setting a new property value.

If we use a strong, then this property may point to a mutable object, which is affected if the Mutable object is modified externally.

Copy of this trait expresses a relationship similar to strong. However, the set method does not retain the new value, but instead copies it. When the property type is nsstring, this trait is often used to protect its encapsulation, because the new value passed to the set method may point to an instance of the Nsmutablestring class. This class is a subclass of NSString, which represents a string that modifies its value, and if you do not copy the string, the value of the string may be changed without the object's knowledge when the property is set. Therefore, a copy of the "Immutable" (immutable) string is necessary to ensure that the string values in the object are not inadvertently changed. As long as the object used to implement the property is "mutable" (mutable), a copy should be made when setting the new property value.

4.runloop, Autorelease Pool, and the relationship between threads.

Each thread (including the main thread) has a runloop. For each runloop, the system implicitly creates a autorelease pool so that all the release pool forms a stack structure like callstack, at the end of each runloop, the current stack top autorelease The pool will be destroyed so that every object in the pool will be release.

What is the nature of [email protected]? How Ivar, Getter, setter are generated and added to this class.

The property has two major concepts: Ivar (instance variable), access method (Access Method=getter), @property = Ivar + getter + Setter.

For example, the following class:

1234 @interface WBTextView :UITextView  @property (nonatomic,copy)NSString *placehold;  @property (nonatomic,copy)UIColor *placeholdColor;  @end

After the completion of the properties of the class, the compiler will automatically write methods to access these properties (auto-synthesize autosynthesis), and the above code writes out the class equivalent to the following code:

123456 @interface WBTextView :UITextView  - (NSString *)placehold;  -(void)setPlacehold:(NSString *)placehold;  -(UIColor *)placeholdColor;  -(void)setPlaceholdColor:(UIColor *)placeholdColor;  @end

Detailed introduction See: http://blog.csdn.net/jasonjwl/article/details/49427377

6. Write a setter method to complete @property (nonatomic,retain) NSString *name and @property (nonatomic,copy) NSString *name

The setter method of the Retain property is to preserve the new value and release the old value, and then update the instance variable to point to the new value. Order is important. If the new value is not retained and the old value is released, and two values point to the same object, the first release operation may cause the system to recycle the object permanently.

123456789101112 -(void) SetName: ( nsstring *) name {      [name retain];      [_name release];      _name = name; } -(void) SetName: (nsstring *) name {             [_name release];      _name = [name copy];

7. Talk about the difference between assign vs Weak,_block vs _weak

Assign applies to basic data types, weak is for NSObject objects, and is a weak reference.

Assign actually the page can be used to modify the object, then why not use it? Since the object modified by assign is released, the address of the pointer still exists, which means the pointer is not set to nil. If in subsequent memory allocations, the address has just been assigned, the program will crash. The pointer address is set to nil after the weak modified object is released.

_block is used to modify a variable that can be modified in a block.

_block: Variables modified with _block are retain in block code blocks (under ARC, MRC does not retain)

_weak: Variables modified with _weak are not retain in block code blocks

8. Please say if there is a problem with the code below, if you have any questions, please change it.

123456 < Code class= "JS plain" > @autoreleasepool  {        &NBSP;&NBSP, for   (int i=0; i[ largenumber; i++)  {  (for identification problems, the line code is replaced with angle brackets instead of square brackets)               person *per =  [[person alloc] init]; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; [per autorelease]; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; &NBSP;&NBSP;&NBSP;&NBSP; }

The principle of memory management: If you use Alloc, copy, retain for an object, you must use the appropriate release or autorelease. I see, this topic has alloc, also have autorelease, the two correspond together, should have no problem. But although Autorelease will reduce the reference count by one, it is not immediately reduced by one, and its essential function is simply to place the object in the auto-release pool closest to him. When the auto-free pool is destroyed, the release message is sent to each object in the auto-free pool. The problem in this question is autorelease. Because Largenumber is a large number, Autorelease does not immediately reduce the reference count by one, so there is a memory overflow problem before the loop ends.

The solution is as follows:

12345678 @autoreleasepool {        for(int i=0; i[100000; i++) { (因识别问题,该行代码中尖括号改为方括号代替)            @autoreleasepool {            Person *per = [[Person alloc] init];            [per autorelease];        }      }    }

Add an auto-release pool inside the loop, which guarantees that every object created will be released in a timely manner.

9. Is there a problem with the following code, please revise it if you have any questions?

123456789 @autoreleasepool {        NSString *str = [[NSString alloc] init];        [str retain];        [str retain];        str = @"jxl";        [str release];        [str release];        [str release];}

This problem is the same as the 8th one. Memory leaks, 1. Memory leaks 2. An object pointing to a constant area cannot be released.

Pointer variable STR originally points to a block of open heap space, but after re-assigning to STR, the direction of STR changed, from the original point to the heap space, to the constant area. The variable in the constant zone does not need to be released at all, which results in the original heap space not being released, as a memory leak.

10. What is the difference between using the weak keyword and comparing assign? What is the use of the weak keyword?

    • In Arc, when a circular reference is likely to occur, it is often resolved by letting one end use weak. Like delegate agent.

    • You have already made a strong reference to it, there is no need to strongly reference it again, you will also use weak, custom control properties are generally used weak.

Different points:

    • Weak this trait indicates that the attribute defines a "non-owning relationship." When you set a new value for this property, the setting method neither preserves the new value nor releases the old value. This attribute is the same as assign, but the property value is also emptied when the object referred to by the property is being pushed down. Assign's "Setup method" only performs simple assignment for the scalar type, such as CGFloat or Nslnteger.

    • Assign can use non-OC objects, and weak must be used for OC objects.

11. Memory management Semantics (differences between assign, strong, weak, etc.)

    • Assign "Set method" only performs simple assignment for "scalar".

    • Strong this trait indicates that the attribute defines an "owning relationship". When you set a new value for this property, the set method retains the new value, frees the old value, and then sets the new value up.

    • Weak this trait indicates that the attribute defines a "non-owning relationship." When you set a new value for this property, the setting method neither preserves the new value nor releases the old value. This trait is similar to assign, but the property value is also emptied when the object referred to by the attribute is pushed down.

    • Unsafe_unretained The semantics of this trait are the same as assign, but it applies to the "Object type," which expresses a "non-owning relationship", which differs from weak when the target object is pushed down and the property value is not automatically emptied.

    • Copy of this trait expresses a relationship similar to strong. However, the set method does not retain the new value, but rather the set method does not retain the new value, but instead copies it. When the property type is nsstring*, this trait is often used to protect its encapsulation, because the new value passed to the set method may point to an instance of the Nsmutablestring class. This class is a subclass of NSString that represents a string that can modify its value, and if the string is not copied, the value of the string may be changed without the object's knowledge. So, copy a "immutable" string to ensure that the string value in the object does not change unintentionally. As long as the object used to implement the property is "mutable," a copy should be made when setting a new property value.

Follow-up will continue to increase the content of memory management, as well as multi-threaded content, continuously updated ...., please look forward to!

iOS Classic test Summary--memory management

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.