Cainiao-objective-C

Source: Internet
Author: User

Note: This is a summary of objective-C syntax translated by netizens.ArticleI think the original text is well written and can be translated, so I will show it here.

 

Click to download a Chinese PDF FileHere.

=============================================================== Separation line = ==========================================

Learn objective-C

Original article addressHttp://cocoadevcentral.com/d/learn_objectivec/

 

Translator's preface

I saw this article on the Internet and thought it was very good, but it seems that no one has translated it into Chinese, so I am bold enough to translate it. I have been developing software for six years, but most of them are on Windows platforms. Recently I installed a leopard on my machine and I am a newbie in objective-C, whether the translation in this article is in place is still playing a drum. If you find that the translation is incorrect, contact me. My fuel tank is cchenhao at gmail dot com.

CC is good. J. Thank you.

 

Objective-C

Objective-C is the main tool for developing Mac software.Programming Language. If you understand some basic object-oriented concepts and C language, it will be helpful for you to learn objective-C. If you do not know C, you are advised to read the C guide first.

This guide is written and illustrated by Scott steven son.

 

Method call

To get started as soon as possible, let's take a look at some examples.

The basic syntax for calling an object method is as follows:

 

[Object method];

[Object methodwithinput: Input];

 

Methods can return values:

 

Output = [object methodwithoutput];

Output = [object methodwithinputandoutput: Input];

 

You can also call the class method, which is also a way to create an object. In the following example, we call the string method of the nssting class to return a new nsstring class object.

 

Id myobject = [nsstring string];

 

The ID type means that the variable myobject can be any type of object. So when you compile this sectionCodeIts actual type and the method compiler it implements are unknown. In our example, the object type is obviously nsstring, so we can change the object type declaration:

 

Nsstring * mystring = [nsstring string];

 

Now, this is an nsstring type variable. If we call a method that is not supported by an nsstring type object on this object, the compiler will issue a warning.

Note: There is an asterisk (*) on the right side of the object type. In objective-C, all object variables are pointer types. The ID type has been predefined as the pointer type, so you do not need to add an asterisk.

 

Nested call

In many programming languages, nested methods or function calls look like this:

 

Function1 (function2 ());

 

The return value of function2 is passed to function1 as an input parameter. In objective-C, nested calls look like this:

 

[Nsstring stringwithformat: [prefs format];

 

Avoid nesting more than two layers in a row of statements, which will reduce the readability of the Code.

 

Multiple Input parameters

Some methods require multiple input parameters. In objective-C, a method name can be split into several segments. In the header file, the method declaration with multiple input parameters looks like this:

 

-(Bool) writetofile :( nsstring *) path

Atomically :( bool) useauxiliaryfile;

 

You can call this method as follows:

 

Bool result = [mydata writetofile: @ "/tmp/log.txt" atomically: No];

 

These are not named parameters. In the runtime environment, the method name is actuallyWritetofile: atomically:

 

Accessors

In objective-C, all instance variables are private by default. Therefore, in most cases, you should use the accessors to obtain or set the values of these variables. There are two types of syntax. The following is the traditional 1.x Syntax:

 

[Photo setcation: @ "day at the beach"];

Output = [Photo caption];

 

The first line of code does not directly read instance variables. In fact, it is calling the method named caption. In objective-C, you do not need to add a "get" prefix before the getter in most cases. In any case, the code in square brackets means that you are sending a message (a method call) to an object or a type ).

 

Point Operator

In Mac OS X 10.5, objective-C 2.0 adds the setter and getter operators of the vertex OPERATOR ):

 

Photo. Caption = @ "day at the beach ";

Output = photo. Caption;

 

You can use either of the two syntaxes, but you 'd better use only one of them in a project. At the same time, the dot syntax can only be used on Setter and getter, but not for common methods.

 

Create object

There are two main methods to create an object. The first one is what you saw earlier:

 

Nsstring * mystring = [nsstring string];

 

This is a more convenient and natural way. In this way, you create an automatic release(Autoreleased)Object. We will see more details later. However, in many places, you may need to create an object manually, as shown below:

 

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

 

This is a nested method call. The first is the alloc method call of the nsstring class. This is a relatively low-layer call, which is used to allocate memory and instantiate an object. The second is to call the newly created objectInitMethod. The init method usually performs object initialization settings, such as creating instance variables. As a class user, you cannot know the implementation details of these methods. In some cases, you can useInitAnother method version with input parameters:

 

Nsnumber * value = [[nsnumber alloc] initwithfloat: 1.0];

 

Memory management basics

When you write applications for Mac OS XProgramYou 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:ReleaseAndAutorelease. 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])

{

[Selfsetcaption: @ "Default caption"];

[Selfsetphotographer: @ "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 [Super dealloc] Message, requiring the parent class to be cleaned up. 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.

 

Log records

In objective-C, it is very easy to output log information to the console. In fact, the nslog () function is similar to the printf () function in C language.% @A symbol represents an object.

 

Nslog (@ "the current date and time is: % @", [nsdate date]);

 

You can output the information of an object as a log in the console. The nslog function calls the description method of this object and prints the nsstring returned by this method to the console. You can rewrite this method in your class to return your custom string.

 

Property (Properties)

We have previously written caption and author access methods. You may have noticed that the code is simple and can be written in a more universal form. Attribute is a feature of objective-C. It allows us to automatically generate accessors and has other benefits. We use attributes to rewrite the photo class.

The previous code looks like this:

 

# Import <Cocoa/cocoa. h>

@ Interface photo: nsobject {

Nsstring * Caption;

Nsstring * photographer;

}

-(Nsstring *) caption;

-(Nsstring *) photographer;

-XA (void) setcaption: (nsstring *) input;

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

@ End

 

The code after rewriting with properties looks like this:

 

# Import <Cocoa/cocoa. h>

@ Interface photo: nsobject {

Nsstring * Caption;

Nsstring * photographer;

}

@ Property (retain) nsstring * Caption;

@ Property (retain) nsstring * photographer;

@ End

 

@ PropertyIs an objective-C language instruction that declares attributes. The "retain" with parentheses indicates that the setter must retain the input value. The type and name of the specified attribute are followed by the row. Let's take a look at the implementation of this class:

 

# Import "photo. H"

@ Implementation photo

@ Synthesize Caption;

@ Synthesize photographer;

-(Void) dealloc

{

;

[Photographer release];

[Super dealloc];

}

@ End

 

@ Synthesize command generates setter and getter for us, so all we have to do is implement the dealloc method. Only when the accesser does not exist will @ synthesize automatically generate the accesser. Therefore, even if @ synthesize is used to declare an attribute, you can still implement custom getter and setter. The compiler will only automatically generate methods that you do not have a custom method. Attribute Declaration has many options, but they are beyond the scope of this Guide.

 

Call methods on Nil

In objective-C, nil Objects Act as null pointers in many other languages. The difference is that calling methods on nil does not cause program crashes or throws exceptions. This technology is used in many places, but for us, the most important thing is that we do not need to check whether the object is empty before calling the method of an object. If you call a nil object method and the method returns a value, you will get a nil return value. We can also use it to slightly improve our dealloc method:

 

-(Void) dealloc

{

Self. Caption = nil;

Self. Photographer = nil;

[Super dealloc];

}

 

This can be done because when we assign the nil value to an instance variable, the setter will release the old object and keep the NIL object. This method is better for dealloc, because it avoids pointing the variable to a random data, and this data happens to be another object. Note: here we use the self. <var> syntax, which indicates that we use setter, which manages the memory. If we only set the value directly, as shown below, memory leakage will occur:

 

// Incorrect. causes a memory leak.

// Use self. caption to go through setter

Caption = nil;

 

Category (Category)

Category is one of the most useful features in objective-C. In essence, a category allows you to add methods to an existing class without subclass or understanding the implementation details of this class. This is especially useful because you can add methods to a built-in object. To add a method to all nsstring instances in your application, you only need to add a category instead of defining a subclass to add the method. For example, if I want to add a method to nsstring to determine whether it is a URL, the statement is as follows:

 

# Import <Cocoa/cocoa. h>

@ Interface nsstring (utilities)

-(Bool) isurl;

@ End

 

This is similar to the declaration of a class. The difference is that the parent class is not listed at the end, and the name of the category is written in brackets. The name of a category can be obtained at will, but it is best to express what you want to do in the method included in the category.

The following is an implementation. Remember, this is not a good way to check the URL. We just want to clarify the concept of the category.

 

# Import NSString-Utilities.h"

@ Implementation nsstring (utilities)

-(Bool) isurl

{

If ([self hasprefix: @ "http: //"])

Return yes;

Else

Return no;

}

@ End

 

Now you can use this nsstring method. The following code prints "string1 is a URL" on the console ":

 

Nsstring * string1 = @ "http://pixar.com /";

Nsstring * string2 = @ "Pixar ";

If ([string1 isurl])

Nslog (@ "string1is a URL ");

If ([string2 isurl])

Nslog (@ "string2is a URL ");

 

Unlike subclass, you cannot add instance variables by category. However, you can use existing methods in the override class. Of course, you must be especially careful when rewriting. Remember, when you change a class through a category, this change will affect all instances of this class in your application.

 

Summary

This article introduces basic objective-C knowledge. As you can see, this language is very easy to learn. It does not have many special syntaxes, and many standards are also used multiple times in cocoa. If you like the examples above, you can download the project and view itsSource code.

Learnobjectivec xcode 3.0 Project (56 K)

Http://cocoadevcentral.com/downloads/LearnObjectiveC-20080414a.zip

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.