From c to C + + to obj-c memory Management Learning notes (iii)

Source: Internet
Author: User

The first two describes the memory management of C and C + +, which describes the memory management of OBJECT-C.


Object-c is a superset of C, and all C-language features can be implemented in object-c.

However, there are still some differences in memory management.

Object-c is the object-oriented C language, and most of its types are based on the cocoa framework, with the usual NS opening types.

So most of the types in Object-c are class-based.

OBJECT-C classes are stored in heaps rather than stacks, so generic class object definitions are in the form of pointers, such as:

<span style= "FONT-SIZE:18PX;" >nsstring * str = @ "TEST";</span>

Instead of the automatic variable type in C + + form:

<span style= "FONT-SIZE:18PX;" >nsstring test; Error</span>

There are also non-class type non-object types in object-c, such as the types implemented in C-language structures such as Cgrect,cgpoint,

According to the management rules of C, these types also belong to the category of automatic variables in the local code block.

Object-c is a superset of C, probably because I see less information, in the current view of the OBJECT-C data, compared to less mention of similar to the memory management keywords mentioned in C,

Memory-sensitive classes, and so on. However, since it is a superset of C, then whether it is the keyword or memory area classification, it should be very much the same, this is a big God familiar with the trouble in the comment area below to let me know.

The following refers to the memory area of the previous section of the image to illustrate the OBJECT-C memory partition:


As described in the previous article of the role of the district, here no longer repeat.

Const in OBJECT-C has a constant area, extern,static is stored in a static storage area, and the static variables in the five storage classes in C can still be used in object-c, such as:

<span style= "FONT-SIZE:18PX;" >static cgfloat Coordinatorx = 0.6;extern Nsinteger sum = 2;//function in static Bool flag = 1;</span>
<span style= "FONT-SIZE:18PX;" >static Const FLOAT = 2.0;</span>

Non-object's automatic variables are stored on the stack, such as:

<span style= "FONT-SIZE:18PX;" >viewdidload {Nsinteger num = 1; CGFloat x = 2; CGFloat y = 3;} </span>

and class variables are stored in the heap.


Object-c used a garbage collection mechanism similar to garbegecollection to manage memory in the early days, but was later replaced by MRC and now replaced by arc.

The above mentioned Object-c objects are put in the heap, but also dynamic generation, this is object-c and C in memory management of the biggest difference and object-c characteristics.

Garbegecollection,mrc,arc, for example, is used to manage, generate, and release objects, such as malloc ()-free () in C, which is managed in another way.


MRC and Arc

OBJECT-C's memory management introduces the concept of reference counting Retaincount, as the name implies is how many pointers point to the current object, and when the reference count is 0 o'clock, the object is freed.

Both MRC and ARC are based on runtime dynamic implementation, reference count + 1,-1, Object release message is sent by runtime to implement.


MRC (Manual Reference counting)

MRC translated into Chinese is a manual reference count, in the MRC and C language, there are some keywords, generally used for attribute declarations.

There are several main, retain,assign,copy,release.

Note that the following example code is in the MRC environment!!!

Retain

When declaring a property with retain, such as:

<span style= "FONT-SIZE:18PX;" > @property (retain) NSString *name;</span>

So when we assign a string object to name, the reference count of the string Retaincount +1.


It can also be used directly when generating objects, such as:

<span style= "FONT-SIZE:18PX;" >nsstring *temp = [[NSString stringwithstring:@ "Hello World"] retain];</span>

This way the object reference count is also + 1.

The implementation in Accessmethor is this:

<span style= "FONT-SIZE:18PX;" >-(void) Name: (NSString *) name {if (self.name! = name) {[Self.name release];self.name = [name retain];}} </span>



Assign

Assign in contrast to retain, when used for a property declaration, it is simply an assignment and the reference count is the same as:

<span style= "FONT-SIZE:18PX;" > @property (assign) Nsinteger *age;</span>
and is generally only used for simple data types, such as Nsinteger,nsuinteger.

The implementation in Accessmethor is this:

<span style= "FONT-SIZE:18PX;" >-(void) Age: (Nsinteger *) Age {self.age = age;} </span>
It is important to note that assign point object is released when assign object is not known, this is if the use of the words will crash, called Wild Pointer.


Copy

Copy as the name implies is assignment, when the object assignment, copy the new object to be assigned, the original object is unchanged, such as:

<span style= "FONT-SIZE:18PX;" > @Property (copy) NSString *str; NSString *temp = @ "Hello world"; self.str = temp;</span>

At this point the object reference count of temp is constant, and the new object is assigned to STR, reference count +1;

The implementation in Accessmethor is this:

<span style= "FONT-SIZE:18PX;" >-(void) str: (NSString *) str {if (self.str! = str) {[Self.str release];self.str = [str copy];}} </span>

You can also use the same as retain when generating objects:

<span style= "FONT-SIZE:18PX;" >nsstring *temp = [[NSString stringwithstring:@ "Hello World"] copy];</span>
the original object is automatically freed and the new object is assigned to temp.


Release

Release is a reference count minus one, releasing an object from a pointer using release, as in the above:

<span style= "FONT-SIZE:18PX;" >[self.str release];</span>
the object is automatically destroyed when Retaincount is 0 o'clock.


MRC is a manual management of reference counting, which is cumbersome for program apes, with little attention to issues such as wild pointers and memory leaks.

The benefit of MRC's memory management approach compared to C is that using reference counting simplifies the release process and is more secure.

In C language, for example, if you have multiple references to the same object, and once it has been released in one place, the other becomes a wild pointer, which is more dangerous.

The advantage of MRC is that, if used properly, the reference count is reduced to 0 o'clock only after the object is released everywhere, so it is not easy to have wild pointers.

However, the MRC is still more difficult to operate, requiring the program ape to clear at all times what objects should be released and what should not. Apple introduced the ARC automatic application count after iOS5, which greatly facilitated the work of the program ape.


ARC (Auto Reference counting)

The introduction of Arc further facilitates the memory management of objects in OC. It introduces three new keywords, strong,weak,unsafe_unretained.

With these three new keywords, we don't need to manually manage the reference count, just attach the keyword when declaring the variable.

These three keywords are described below:


Strong

Strong and MRC have similar retain functions, called strong references.

Apply to attribute declarations:

<span style= "FONT-SIZE:18PX;" > @property (Strong) NSString *name;</span>
the object reference count is automatically +1 when the value is assigned, and when name points to other objects, the original object reference count is automatically reduced by one without manual release.

It can also be used in temporary variables, such as:

<span style= "FONT-SIZE:18PX;" >__strong NSString *str; NSString *str1 = @ "Hello world"; str = str1;</span>
This is the string object reference count of +1.

It is worth noting that the temporary variable defaults to the strong type.


Weak

Weak and MRC have similar assign functions, which are called weak references.

Apply to attribute declarations:

<span style= "FONT-SIZE:18PX;" > @property (weak) NSString *name;</span>
The object reference count is constant at assignment, and when name points to other objects, the original object is automatically freed without manual release.

It can also be used in temporary variables, such as:

<span style= "FONT-SIZE:18PX;" >__weak NSString *str; NSString *str1 = @ "Hello world"; str = str1;</span>
The string object reference count is not changed at this time.

When STR1 is set to nil, STR does not become a wild pointer, and unlike assign, STR is automatically set to nil, so it is more secure.

Weak is used to eliminate circular references in arcs, such as circular references in blocks, or for delegate.



unsafe_unretained

Unsafe_unretained and weak are very similar, are only assignment, the reference count is not changed, but unsafe_unretained as the name implies is unsafe, such as:

<span style= "FONT-SIZE:18PX;" > @property (unsafe_unretained) NSString *name;</span>

It can also be declared in a local variable, such as:

<span style= "FONT-SIZE:18PX;" >__unsafe_unretained NSString *str; NSString *str1 = @ "Hello world"; str = str1;</span>
when STR1 is released, STR becomes a wild pointer, which is unsafe.

It is important to note that the Class property defaults to the unsafe_unretained type.


This is more convenient than MRC,ARC, but there are also problems with the memory leaks caused by circular references, which need to be paid more attention to when using.


Summary:

Object-c is a superset of C, there are stacks, heaps, static storage areas, constant areas, etc. in memory management, except that object-c have the object variable and Non-object variable. The Non-object variable is roughly the same as the automatic variable in C, and is an automatic variable on a local block of code that is stored on the stack. The object variable is somewhat different from C and is dynamically generated, similar to malloc ()-free () in C, which is stored in the heap. Object-c thus introduces dynamic runtime-based management mechanisms such as GABEGECOLLECTION,MRC,ARC, based on reference counting, to Retain,weak,copy,unsafe_unretained,strong, Assign and other keywords to manage reference counts. ARC is relatively easy to use with MRC and does not have to be manually released by the program Ape, but there are also disadvantages such as circular referencing.

The next article introduces EventLoop and Autoreleasepool, and C,c++,object-c's comparative summary.

From c to C + + to obj-c memory Management Learning notes (iii)

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.