Objective-c Memories Management Memory Management The first part

Source: Internet
Author: User

Objective-c Memory Management?? Memory management?? The first part

Memory Management is part of a more general problem in programming called resource management.

Memory management is part of resource management.

Every computer system have finite resources for your These include memory, open files, and network connections. If you use a resource, such as by opening a file, you need to clean up after yourself (in this case, by closing the file).

Each computer has limited resources. Includes memory, number of open files, network connection. If you open a file, you should clean it up.

Our friends in
The Java and scripting worlds has it easy:memory management happens automatically for them, like has their parents cl Ean up their rooms.

Java? and its scripting World is easy: memory management is automatic for them. Like a father who cleans up his child's room.

If we allocate without freeing, we'll leak Memory:our program ' s memory consumption would grow and grow until we run out of Memory, and then, the program would crash.

If memory is allocated, but not recycled, it can lead to memory leaks: Our program takes up more and more memory until it runs out of memory, and the program crashes.

1.1 Object life Cycle?? Object Declaration Period

Just like the birds and the bees out of here in the real world, objects inside a program has a life cycle. They ' re born (via Alloc or new); They live (receive messages and do stuff), make friends (via composition and arguments to methods), and eventually Die (ge T freed) when their lives is over. When that happens, their raw materials (memory) is recycled and used for the next generation.

Just like real-world birds and bees, objects within a program also have a life cycle. They are born (through Alloc and new), they live (receive messages and things), they make friends (through combinations and parametric methods) and eventually die. In this way their original material (memory) is recycled and reused. That's the same as people ah Ah.

1.2 Reference counting?

Cocoa uses a technique known as reference counting, also sometimes called retain counting.

Use reference count or hold count.

Every object has a integer associated with it, known as its reference count or retain count.

Each object has its own reference count

When some chunk of code was interested in an object, the code increases the object ' s retain count, saying, "I am interested In the This object. When that code was done with the object, it decreases the retain count, indicating that it had lost interest in that object .

With the code interested in an object, add retain count. If you have finished processing, reduce retain count.

When the retain count goes to 0, nobody cares on the object anymore (poor object!), so it's destroyed and its memory I S returned to the system for reuse.

When retain count is 0 o'clock, it waits to be recycled or disposed of.

When a object is about to being destroyed because its retain count has reached 0, Objective-c automatically sends the object A DEALLOC message.

If an object is to be destroyed because retain count? reached 0

To find out the current retain count, send the Retaincount message. Here is the signatures for retain, release and Retaincount:

-(ID) retain;?

-(OneWay void) release;

-(Nsuinteger) Retaincount;

A retain call returns an ID. This enables-chain a retain call with other message sends, incrementing the object's retain count and then asking I T to does some work. For instance, [[car retain] settire:tire Atindex:2]; asks car to bump up its retain count and perform the Settire action.

A retain? Call can increase retain count, and then ask it to do some work.

1.3 Object ownership?

When something was said to ' own an object, ' that something was responsible for making sure ' the object gets cleaned up.

When you say you have this object, then you have to wipe your butt for him. :-)

1.4 Retaining and releasing in accessor?

?

-(void) Setengine: (Engine *) newengine

{

engine = [newengine retain];

?//Bad Code:do not steal. See fixed version below.

}//Setengine

Engine *engine1 = [engine new]; Count:1

[Car setengine:engine1]; Count:2

[Engine1 release]; Count:1

Engine *engine2 = [engine new]; Count:1

[Car setengine:engine2]; Count:2

oops! We have a problem with engine1 Now:its retain count is still 1.

Engine1 retain count? is still 1.main () has released its index to the engine1, but car does not.

?

Here's another attempt at writing Setengine:.

Another form of Setengine method

-(void) Setengine: (Engine *) newengine

{

? [Engine release];

engine = [newengine retain];

More bad code:do not steal. Fixed version below.

}//Setengine

?

?

Engine *engine = [engine new]; Count:1

Car *car1 = [car new];

Car *car2 = [car new];

[Car1 Setengine:engine]; Count:2

[Engine release]; Count 1

[Car2 setengine: [car1 engine]]; oops!

[CAR1 engine] Returns a pointer to engine, which have a retain count of 1. The first line of Setengine is [engine release], which makes the retain count 0, and the object gets deallocated.

?

[CAR1 engine] Returns a pointer to the engine, its retain count? is 1? And the first line of Setengine is the release engine? So retain count? is 0. The object is therefore reassigned.

?

Here's a better-to-write Setengine:

This setengine? Better:

-(void) Setengine: (Engine *) newengine

{

? [Newengine retain];

? [Engine release];

engine = Newengine;

}//Setengine

In your accessors, if you retain the new object before your release the old object and you'll be safe.

In the store, if you keep the new object before you release the object for long. Then you'll be safe.

?

1.5Autorelease?? Automatic release

Cocoa has the concept of the autorelease pool.

Cocoa? There is the concept of an auto-release pool.

The name provides a good clue.

It's a Pool (collection) of stuff, presumably objects, that automatically gets released.

It can be seen from the name that it is probably something that is automatically released.

NSObject provides a method called Autorelease:

-(ID) autorelease;

This method schedules A, release message to being sent at some time on the future. The return value is the object, the receives the message; Retain uses this same technique, which makes chaining together calls easy. When you send a autorelease to a object, that's object is actually added to
An autorelease pool. When this pool is destroyed, all the objects in the pool is sent a release message.

This method plans a release signal to be sent out. When you send a autorelease? to an object, the object will be added to the Autorelease pool. When the pool is released, all objects in this pool will be issued a release message.

?

-(NSString *) description

{

? NSString *description;

? description = [[NSString alloc]

? Initwithformat: @ "I am%d Years old", 4];

return ([description autorelease]);

}//Description

So you can write the code like this:

NSLog (@ "%@", [someobject description]);

?

1.6. The eve of destruction? The Eve of our destruction

When does the Autorelease pool get destroyed so, it can send a release message to all the objects it contains? For this matter, when does a pool get created in the first place?

When does the automatic release pool be destroyed and when is the resource pool created?

?

There is ways you can create a autorelease pool.

There are two ways of creating:

(1) Using the @autoreleasepool language keyword.

(2) Using the NSAutoreleasePool object.

The first kind: @ autoreleasepool{}?. Inside the curly braces will be placed in the new pool.

The second, and more explicit, method are to use the NSAutoreleasePool object. When you do this, the code between new and release gets the new pool.

The second kind, with NSAutoreleasePool?

NSAutoreleasePool *pool;

Pool = [NSAutoreleasePool new];

...

[Pool release];

?

?

int main (int argc, const char *argv[])

{

? NSAutoreleasePool *pool;

Pool = [[NSAutoreleasePool alloc] init];

? Retaintracker *tracker;

? tracker = [Retaintracker new]; Count:1

? [Tracker retain]; Count:2

? [Tracker Autorelease]; Count:still 2

? [Tracker release]; Count:1

? NSLog (@ "Releasing pool");

? [Pool release];

?//Gets nuked, sends release to tracker

[Email protected]

? {

? ? Retaintracker *tracker2;

? ? Tracker2 = [Retaintracker new]; Count:1

? ? [Tracker2 retain]; Count:2

? ? [Tracker2 Autorelease]; Count:still 2

? ? [Tracker2 release]; Count:1

? ? NSLog (@ "Auto releasing pool");

? }

return (0);

}//Main

?

[Tracker Autorelease]; Count:still 2

Then the object gets autoreleased. Its retain count is Unchanged:it ' s still 2. The important thing to note are that the pool, is created earlier now have a reference to this object.

This object has been automatically released. Its retain count is still 2. But the important thing is pool? Have a reference of this object.?

?

?

?

Objective-c Memories Management Memory Management The first part

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.