Cainiao learning iPhone development-objective-C-Medium

Source: Internet
Author: User

Memory management basics

When you write an application for Mac OSX, you can choose to allow garbage collection. This means that you do not have to consider memory management if it is not particularly complex. However, you will not always work in an environment that supports garbage collection. In this way, you need to know some basic concepts. If you create an object by using manual alloc, you need to release this object. Similarly, you cannot manually release an autoreleased object because it will crash your application.

The following are two examples:

 

// String1 will be automatically released

Nsstring * string1 = [nsstring string];

 

// It must be manually released after use

Nsstring * string2 = [[nsstring alloc] init];

[String2 release];

 

Here, you can think that the automatically released object will be automatically released at the end of the current function.

There are many things to learn about memory management, but we should first understand other concepts so that we will have more knowledge.

 

Design Interface

In objective-C syntax, it is very easy to create a class. A class is usually divided into two parts. Interfaces of a class are usually stored in a similarClassname. hHere, we define the instance variables and public methods. Class implementation is stored inClassname. mSuch a file contains the actual implementation code of these methods. It also defines private methods that the customer class cannot access.

An interface file looks like the following. This class is called photo, so the interface file name isPhoto. h:

 

# Import <Cocoa/cocoa. h>

@ Interface photo: nsobject {

Nsstring * Caption;

Nsstring * photographer;

}

@ End

 

First, we importedCocoa. hTo add basic classes of the cocoa application.# ImportThe command automatically prevents the same file from being imported multiple times.@ InterfaceIndicates this is a classPhoto. Specify the parent class (superclass) after the colon, where the parent class is nsobject. Two instance variables are declared in curly brackets:CaptionAndPhotographer. All are of the nsstring type. instance variables can be of any object type, including the ID type. Finally,@ EndThe Declaration of the symbol end class.

 

Add Method

Let's add some getter to the instance variable)

 

# Import <Cocoa/cocoa. h>

@ Interface photo: nsobject {

Nsstring * Caption;

Nsstring * photographer;

}

Caption;

-Photographer;

@ End

 

Remember, the "get" prefix of methods is usually omitted in objective-C language. A single minus sign (-) before the method name indicates that this method is an instance method. If the method name is preceded by a plus sign (+), it indicates that the method is a class (static) method.

 

By default, the compiler returns an object of the ID type. All input parameters are of the ID type by default. The above code is technically correct, but we generally do not write it like this. We need to specify the return value type for these methods.

 

# Import <Cocoa/cocoa. h>

@ Interface photo: nsobject {

Nsstring * Caption;

Nsstring * photographer;

}

-(Nsstring *) caption;

-(Nsstring *) photographer;

@ End

 

Now let's add the setter ):

 

# Import <Cocoa/cocoa. h>

@ Interface photo: nsobject {

Nsstring * Caption;

Nsstring * photographer;

}

-(Nsstring *) caption;

-(Nsstring *) photographer;

-(Void) setcaption: (nsstring *) input;

-(Void) setphotographer: (nsstring *) input;

@ End

 

The setter does not need a return value, so we specify the return valueVoid.

 

Class implementation

Now, we start with the getter to create a class implementation.

 

# Import "photo. H"

@ Implementation photo

-(Nsstring *) caption {

Return Caption;

}

-(Nsstring *) photographer {

Return photographer;

}

@ End

 

This code starts with the name of @ implementation and class, and there is a @ end like an interface. All methods must be written between the two statements. If you have written the code, you will feel that the above accessors seem familiar, so let's take a look at the seters. They need a little more explanation.

-(Void) setcaption: (nsstring *) Input

{

;

Caption = [input retain];

}

-(Void) setphotographer: (nsstring *) Input

{

[Photographer autorelease];

Photographer = [input retain];

}

 

Each modifier processes two variables. The first is the currently referenced object, and the second is the newly entered object. In an environment with a garbage collection mechanism, we can directly set a new value.

 

-(Void) setcaption: (nsstring *) Input

{

Caption = input;

}

 

However, if you cannot use garbage collection, you needReleaseAndRetainNew object. There are two methods to release an object reference:Release
AndAutorelease. Standard release immediately releases object references. Autorelease will not be released after a while, but the reference will actually exist until the current method ends (unless you add custom code to change it explicitly ). It is safer to use the autorelease method in the configurator, because the new and old values of the variables to be changed may point to the same object. But you may not want to immediately release the objects you actually want to keep. It seems confusing now, but as you keep learning, you will get to know more. Therefore, you do not need to fully understand this.

 

Init

We can create an init method to set the initialization value for our instance variables:

 

-(ID) Init

{

If (Self = [Super init])

{

[Self setcaption: @ "Default caption"];

[Self setphotographer: @ "Default photographer"];

}

Return self;

}

 

This Code does not need to be explained at all, although the second line looks a bit uncommon. It is a single equal sign (=), which is used[Super init]The result is assignedSelf. This actually requires the parent class to perform (parent class) initialization. The IF statement is used to verify whether the parent class is initialized successfully before trying to set (the default value of this object.

 

Dealloc

The dealloc method is called when an object is deleted from the memory. Usually, instance variables in all objects are released in this method.

 

-(Void) dealloc

{

;

[Photographer release];

[Superdealloc];

}

 

In the first two lines, we directly called the release method of instance variables. Here, we do not need to use autorelease because standard release is faster. The last line is very important. We sent a [superdealloc] Message, requiring the parent class to perform cleanup. If we do not do this, the object will not be deleted from the memory, which causes memory leakage. When the garbage collection mechanism is enabled, the object's dealloc method will not be called. In this case, you can implement a Finalize method to replace it.

 

Memory Management

Objective-C memory management is based on reference count. The only thing you need to do is to pay attention to your reference, and the work of releasing memory is actually done by the running environment. In the simplest case, you need to send a release message to the assigned (alloc) object or the objects that are retained in some places. This also means that if you have used alloc once and retained it again, you need to release twice to release the memory of the object.

 

This is the reference counting theory. In actual application, we usually create an object only for two reasons:

1. reserved as an instance variable.

2. Use the function as a temporary variable.

In most cases, the setter of an instance variable will automatically release (autorelease) the originally referenced object and retain (retain) the new one. You only need to ensure that it is released (release) in the dealloc function.

In this case, we only need to locally reference the management function. There is only one rule: if you create an object through alloc or copy, you can send a release or autorelease message to it at the end of the function. If you create an object in other ways, do nothing. The following is the first example to manage instance variables:

 

-(Void) settotalamount: (nsnumber *) Input

{

[Totalamount autorelease];

Totalamount = [input retain];

}

-(Void) dealloc

{

[Totalamount release];

[Super dealloc];

}

 

The following is another example about local references. We only need to release the object created through alloc:

 

Nsnumber * value1 = [[nsnumber alloc] initwithfloat: 8.75];

Nsnumber * value2 = [nsnumber numberwithfloat: 14.78];

// Only release value1, not value2

[Value1 release];

 

The following is a combination example that sets a local reference to an instance variable:

 

Nsnumber * value1 = [[nsnumber alloc] initwithfloat: 8.75];

[Self settotal: value1];

Nsnumber * value2 = [nsnumber numberwithfloat: 14.78];

[Self settotal: value2];

[Value1 release];

 

Note that whether or not you assign values to local references as instance variables, they are all the same. You don't have to consider how setter is implemented. If you understand this, you will understand what you need to know about 90% in objective-C memory management.

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.