Objective, objectivec

Source: Internet
Author: User

Objective, objectivec

Objective-C Memory Management Part 1

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

Memory Management is part of resource management.

Every computer system has finite resources for your program to use. 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. Including memory, number of opened files, and network connections. If you open a file, you should clear it.

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

Java and Its script world are easy: memory management is automatic for them. Just like a father packing up his child's room.

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

If memory is allocated but not recycled, memory leakage may occur: Our program occupies more and more memory until the memory is used up and the program crashes.

1.1 Object Life Cycle Object declaration Cycle

Just like the birds and the bees out here in the real world, objects inside a program have 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 (get freed) when their lives are over. when that happens, their raw materials (memory) are recycled and used for the next generation.

Just like birds and bees in the real world, objects in a program also have lifecycles. They were born (through alloc and new), they lived (to receive messages and things), they made friends (through combinations and parameter methods) and finally died. In this way, their original materials (memory) are recycled and reused. Just like people.

1.2 Reference Counting

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

Use reference count or keep count.

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

Each object has its own reference count

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

If the code is interested in an object, add retain count. If the processing is complete, reduce the retain count.

When the retain count goes to 0, nobody cares about the object anymore (poor object !), So it is destroyed and its memory is returned to the system for reuse.

When the retain count is 0, wait until it is recycled or processed.

When an object is about to be destroyed because its retain count has reached 0, Objective-C automatically sends the object a dealloc message.

If an object will be destroyed because the retain count reaches 0

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

-(Id) retain;

-(Oneway void) release;

-(NSUInteger) retainCount;

A retain call returns an id. this enables you to chain a retain call with other message sends, incrementing the object's retain count and then asking it to do 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 the retain count and then require it to do some work.

1.3 Object ownership

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

When you say you own this object, you should also wipe your ass for it. :-)

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.

The retain count of engine1 is still 1. main () has released its index of engine1, but the 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 has 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. The first line of setEngine is release engine. Therefore, the retain count is 0. Therefore, the object is reassigned.

 

Here's a better way to write setEngine:

This setEngine is better:

-(Void) setEngine: (Engine *) newEngine

{

[NewEngine retain];

[Engine release];

Engine = newEngine;

} // SetEngine

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

In storage, if you keep new objects before you release them for a long time. Then you are safe.

 

1.5 Autorelease automatic release

Cocoa has the concept of the autorelease pool.

Cocoa has the concept of automatically releasing a pool.

The name provides a good clue.

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

The name indicates that it is automatically released.

NSObject provides a method called autorelease:

-(Id) autorelease;

This method schedules a release message to be sent at some time in the future. the return value is the object that contains es the message; retain uses this same technique, which makes chaining together CILS easy. when you send autorelease to an object, that object is actually added
An autorelease pool. When that pool is destroyed, all the objects in the pool are sent a release message.

This method schedules a release signal to be sent. When you send 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 released.

 

-(NSString *) description

{

NSString * description;

Description = [[NSString alloc]

InitWithFormat: @ "I am % d years old", 4];

Return ([description autorelease]);

} // Description

So you can write code like this:

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

 

1.6 Eve of Destruction The Eve of Our Destruction

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

When will the automatic release pool be destroyed, and when will the resource pool be created?

 

There are two ways you can create an autorelease pool.

There are two ways to create:

(1) Using the @ autoreleasepool language keyword.

(2) Using the NSAID oreleasepool object.

First: @ autoreleasepool {}. Put the braces in the new pool.

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

Method 2: Use NSAID utoreleasepool

NSAID utoreleasepool * pool;

Pool = [NSAutoreleasePool new];

...

[Pool release];

 

 

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

{

NSAID utoreleasepool * pool;

Pool = [[NSAID utoreleasepool 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

@ Autoreleasepool

{

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 is that the pool that was created earlier now has a reference to this object.

This object is automatically released. Its retain count is still 2. But it is important that the pool has a reference for this object.

 

 

 

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.