OC Metamorphosis Fifth Day

Source: Internet
Author: User

Summarize
    • Global Breakpoint
      • →-->+-->add Exception Breakpoint
    • Turn on Zombie monitoring

      • Open Edit Scheme-->diagnostics-->enable Zombie Object
    • Retain not only counter + 1, but also return the current object

Marking title content
One Content Management Importance of memory management/memory management concepts/heap and stack/memory management principles/multi-Object memory management/set methods memory management/dealloc methods
Two Reference counter Reference counting Concept/action/action
Three Dealloc Basic concepts of the Dealloc method
Four Wild pointer/null pointer Zombie Object concept/wild pointer concept/NULL pointer concept
Five Xcode settings How to turn off the ARC function/How to turn on zombie object monitoring
Six Property modifier The memory management/control of the control set method requires no generation of the Set method/Multithreading Management/Control set method and the name of the Get method
Seven @class @class Basic Concepts/Application scenarios/@class and #import differences
Eight Cyclic retain Basic concepts of cyclic Retian
I. Memory management
    • Arc:automatic Reference Counting

    • What is automatic reference counting

      • Without the programmer to manage the content, the compiler will automatically add Release/retain and other code to us where appropriate.
      • Note the point:
        • The arc in OC is not the same as the garbage collection mechanism in Java, garbage collection in Java is the system dry, and the arc in OC is the compiler dry
        • Whenever you create an object, the value of the default reference counter is 1.
    • Mrc:manual Reference Counting
    • What is manual reference counting
      • The contents of all objects need to be managed manually, requiring programmers to write their own release/retain and other code
    • Principles of memory management
      • There are plus and minus
1. The importance of memory management
    • The memory of mobile devices is extremely limited, and each app can occupy a limited amount of memory

    • The following behavior increases the memory footprint of an app

      • Create an OC Object
      • Define a variable
      • Call a function or method
    • If the app takes up too much memory, the system may force the app to close, causing a flashback and impacting the user experience

2. What is memory management
    • How do I recycle objects that don't need to be reused?

      • Learn about OC memory Management
    • The so-called memory management, is the memory management, involves the operation is:

      • Allocating memory: Creating an object, for example, increases memory consumption
      • Clear memory: For example, destroying an object can reduce memory consumption
    • Management scope of memory management

      • Any object that inherits the NSObject
      • Not valid for other non-object types (int, char, float, double, struct, enum, etc.)
    • The essential reason why memory management is only required for OC objects

      • OC objects stored inside the heap
      • Non-OC objects are generally placed inside the stack (the stack memory is automatically reclaimed by the system)
3. Heap and Stack
    • Stack (operating System): automatically allocated by the operating system to release, store the function parameter value, local variable value and so on. It operates in a way similar to a stack in a data structure (advanced back-out);

    • Heap (operating system): Usually released by the programmer, if the programmer does not release, the end of the program may be collected by the OS (Operating system), distributed in a manner similar to the list.

    • Example:

int main(int argc, const char * argv[]){    @autoreleasepool {        int a = 10; // 栈        int b = 20; // 栈        // p : 栈        // Person对象(计数器==1) : 堆        Person *p = [[Person alloc] init];    }    // 经过上一行代码后, 栈里面的变量a\b\p都会被回收    // 但是堆里面的Person对象还会留在内存中,因为它是计数器依然是1    return 0;}
4. Memory Management Principles
    • Apple's official policy on memory management

      • Who created who release:

        • If you create an object by Alloc, new, or [mutable]copy], you must call release or Autorelease
      • Who Retain who release:

        • Once you call retain, you must call the release
    • A summary is

      • Plus, there's a minus.
      • Once let the object counter +1, it must be at the end to let the object counter-1
5. Multi-Object Memory management
    • As long as someone else is using an object, the object will not be recycled.
    • As long as you want to use this object, let the object's counter +1
    • When you no longer use this object, let the object's counter-1
6.set Method Memory Management
    • (1) objects to be used by retain
    • (2) The object before release
    • (3) Release and retain are required only if the incoming object is different from the previous one
- (void)setRoom:(Room *)room{    // 避免过度释放    if (room != _room)    {        // 对当前正在使用的车(旧车)做一次release        [_room release];        // 对新车做一次retain操作         _room = [room retain];    }}
Memory management for 7.DEALLOC methods
- (void)dealloc{    // 当人不在了,代表不用房间了    // 对房间做一次release操作    [_room release];    [super dealloc];}
Two. Reference counters
    • Accounted for 4 bytes
1. What is a reference counter
    • How does the system determine when it needs to reclaim the memory that an object consumes?

      • Depending on the object's reference counter
    • What is a reference counter

      • Each OC object has its own reference counter
      • It is an integer
      • Literally, it can be understood as "the number of times an object is referenced"
2. The role of reference counters
    • In simple terms, it can be understood as:

      • A reference counter indicates how many people are using this object
    • The system recycles this object when no one else is using it, which means

      • When the object's reference counter is 0 o'clock, the memory consumed by the object is reclaimed by the system
      • If the object's counter is not 0, the memory it consumes will not be recycled during the entire program run (unless the entire program has exited)
    • Any object you just created, the reference counter is 1

      • When you create an object using Alloc, new, or copy, the object's reference counter defaults to 1.
3. Actions that reference counters
    • Common actions for referencing counters

      • Send an retain message to the object to make the reference counter value +1 (the Retain method returns the object itself)
      • Send a release message to the object to make the reference counter value-1
      • Send an Retaincount message to the object to get the current reference counter value
    • It is important to note that release does not mean destroying \ Reclaiming objects, just counters-1

Three. Basic concepts of the Dealloc1.dealloc method
    • When an object's reference counter value is 0 o'clock, the object is about to be destroyed, and the memory it consumes is reclaimed by the system
    • When the object is about to be destroyed, the system automatically sends an DEALLOC message to the object (therefore, if the Dealloc method has not been called, it can be determined whether the object is destroyed)

    • Role

      • To determine if the object was destroyed.
    • Law

      • When an object references counter = 0 o'clock, the object is about to be destroyed and the dealloc is called.
    • Rewriting of the Dealloc method

      • Typically overrides the Dealloc method, where the related resources are released
      • 一旦重写了dealloc方法, 就必须调用[super dealloc](在MRC环境下),并且放在最后面调用
    • Use note

      • The Dealloc method cannot be called directly
      • Once the object is recycled, the memory it uses is no longer available, and sticking to it can cause the program to crash (wild pointer error)
Four. Wild pointer/null pointer 1. Zombie Object
    • Objects that have been destroyed (objects that can no longer be used)
2. Wild Hands
    • Pointer to zombie object (memory not available)
    • Send a message to the wild pointer will report exc_bad_access error
3. Null pointer
    • There is no pointer to the storage space (there is nil, that is, 0)
    • There's no response to sending a message to the null pointer.

    • A common way to avoid wild pointer errors

      • After the object is destroyed, the pointer to the object changes to a null pointer
      • Because the null pointer in OC sends a message without an error
Five. Xcode settings 1. How to turn off the ARC feature
    • To manually invoke retain, release, and so on, you must turn off the ARC function
      • Item--Bulid Setting/all---Search automatic--> change objective-c Automatic Reference counting to No
2. How to turn on zombie object monitoring
    • By default, Xcode does not control zombie objects, and using a piece of freed memory does not give an error. For easy commissioning, zombie object monitoring should be turned on

      • Edit scheme-->diagnostics-->objective-c after the Enable Zombile Objects play √ number
* Six. Property modifier 1. Control memory management of Set method
    • Retain:release old value, retain new value (for OC object)
      • Retain automatically generates code for getter and setter method memory management
        • The same property modifier cannot be used at the same time
    • Assign: Direct assignment, no memory management (default, for non-OC object types)
      • Assign does not automatically generate getter and setter method memory management code, only generates normal getter and setter methods (default)
    • Copy:release old value, copy new value (typically used for NSString *)
2. Control requires no need to generate set method
    • ReadWrite: Generate both the Set method and the Get method (default)
    • ReadOnly: Only the Get method is generated
3. Multithreading Management
    • Atomic: Low performance (default), only one person at a time
    • Nonatomic: High performance, can be multiple people at a time (this modifier is used more in iOS)
4. Control the name of the set method and the Get method
    • Setter: Set the name of the set method, there must be a colon:
    • Getter: Set the name of the Get method
    • Note: Different types of parameters can be combined to use
Seven. @class [email protected] basic concepts
    • Role

      • You can simply refer to a class
    • Simple to use

      • @class Dog;
      • Just tell the compiler: Dog is a class; it doesn't contain all the contents of the dog class.
    • Specific use

      • Referencing a class in an. h file using @class
      • Use #import in. m files to include the. h file for this class
[Email protected] Other application scenarios
    • For circular dependencies, for example Class A refers to Class B, and Class B also refers to Class A
    • This nesting contains code that compiles errors
#import "B.h"@interface A : NSObject{    B *_b;}@end#import “A.h"@interface B : NSObject{    A *_a;}@end
    • When using @class in two classes to declare each other, there will be no compilation error
@class B;@interface A : NSObject{    B *_b;}@end@class A;@interface B : NSObject{    A *_a;}@end
[email protected] and #import difference
    • The difference in function

      • #import会包含引用类的所有信息 (content), including variables and methods for referencing classes
      • @class just tell the compiler that there is such a class, what information is in this class, completely unaware
    • The difference in efficiency

      • If there are hundreds of header files are #import the same file, or these files are #import, then once the initial header file changes slightly, the subsequent reference to the file of all the classes will need to recompile again, the compilation efficiency is very low
      • In relative terms, this is not the case with the @class approach.
Eight. Cyclic retain1. Basic concepts of cyclic Retian
    • The scene of the cyclic retain

      • For example a object retain a B object, B object retain a object
    • The drawback of circulating retain

      • This causes the A object and the B object to never be freed
    • Solutions for circulating retain

      • When both ends are referenced, one end should be retain, one end with assign

OC Metamorphosis Fifth Day

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.