Objective-C language tutorial (required for Apple development and iPhone Development)

Source: Internet
Author: User

 

Objective-C syntax

Translate: sprouting stone

2010-03-10

Post please indicate to transfer Apple development Chinese Network (http://www.CocoaDev.cn)

The preceding description is an integral part of this document.

 

Objective-C is the most important language in Mac software development. If we are familiar with object-oriented thinking in C language, it will be very useful for us to learn objective-C. If we are not familiar with the C language, we need to learn the C language.

 

MethodTuneUse (Calling Methods)

To get started as soon as possible, let's take a look at some simple examples. The basic method call in the objective-C syntax is as follows:

 

[Object method];

[Object methodwithinput: Input];

 

Object methods can return values:

Output = [object methodwithoutput];

Output = [object methodwithinputandoutput: Input];

 

We can also call the method for creating objects in the class. In the following example, we callStringMethod:

 

Id myobject = [nsstring string];

 

The ID type meansMyobjectThis variable can point to any type of variable. When we compile this application, we do not know the real classes and methods it implements.

 

In this example, it is obvious that the object type isNsstringSo we can change its type:

 

Nsstring * mystring = [nsstring string];

 

Mystring isNsstringType variable. In this case, if we try to use a method that is not implemented by nsstring, the compiler will warn us.

 

Be sure to have an asterisk on the right of the object type. All objective-C object variables are pointer-type.IDThe type has been pre-defined as a pointer type. Therefore, we do not need to add asterisks.

 

Nested messagesTuneUse (Nested messages)

Nesting messages or nested functions in many programming languages looks like this:

 

Function1 (function2 ());

 

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

 

[Nsstring stringwithformat: [prefs format];

 

We should try to avoid nesting more than two calls in one line of code. In this case, the Code is not very readable.

 

Multiple ParametersInputMethod (Multi-input methods)

Multiple input parameters. In objective-C, a method name can be divided into several segments. In the header file, we should define a method with multiple input parameters as follows:

 

-(Bool) writetofile :( nsstring *) path atomically :( bool) useauxiliaryfile;

 

Let's call it like this:

 

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

 

The parameter does not have to be named. The real name of this method in the runtime system isWritetofile: atomically:.

 

 

2

Accessors

All instance objects in objective-C are private by default. In most cases, we need to use accessors to read or set the value of a variable. There are two syntaxes that support such operations. In this case, the traditional old Syntax:

 

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

Output = [Photo caption];

 

The second line of code does not actually directly read the variables of the object instance. In fact, it callsCaption. In objective-C, we do not need to add the get prefix to getters in most cases.

No matter when we see square brackets, we actually send a message to an object or a class.

 

Dot syntax

In objective-C 2.0, a new "." Operation syntax is added. In Mac OS X 10.5, the objective-C 2.0 syntax is used:

 

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

Output = photo. Caption;

 

We can use both methods. However, it is best to keep the style consistent in a project and use only one of them. The "." operation can only be used in setters and getters, but not in general.

 

 

3

Create object

 

You can create an object in two ways. The first method is as follows:

 

Nsstring * mystring = [nsstring string];

 

This is a very habitual style. In this case, we create an automatic release (Autoreleased. About automatic release typesAutoreleasedIn the future, we will discuss it in depth. However, in many cases, we need to manually create objects:

 

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

 

This is a nested method call. The nsstring of the first callAllocMethod. This is a relatively underlying call, because it creates content and instantiates an object.

 

The second code callsInitMethod. ThisInitMethods, such as parameters for creating instance objects. For general developers, the detailed implementation of this customer's class is not clear.

 

In some cases, we can assign an initial value through initialization without passing through the following methods:

 

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

 

 

4

 

Basic Memory Management

If we are developing an application for Mac OS X, we can choose whether to enable the garbage collection mechanism. This means that we do not need to consider memory management, except for a particularly complicated situation, we need to deal with it.

 

However, sometimes our development environment does not have a garbage collection mechanism, for example, there is no garbage collection mechanism during iPhone development. In this case, we need to understand some basic memory management concepts.

 

If we manually passAllocAn object is created. After this object is used upReleaseIt. We do not need to manually release an autoreleased object. If we do this, our application will crash.

 

There are two examples:

 

// String1 will be released automatically

Nsstring * string1 = [nsstring string];

 

// Must release this when done

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

[String2 release];

 

In this tutorial, The autoreleased object will be released after the current function method is called.

 

Of course, we still need to learn a lot about memory management, but we need to know more about the basic concepts before it can be involved.

 

5

 

DesignA ClassInterface

In objective-C language, it is very easy to create a class. It is typically divided into two parts.

 

Class interfaces are usually stored inClassname. hFile, which defines the instance parameters and some public methods.

 

Class implementation inClassname. mFile. It contains the real running code and the methods. It also often defines some private methods. These private methods are invisible to sub-classes.

 

Here is a rough idea of an interface file. Class Name photo, so the file name isPhoto. h:

 

# Import <Cocoa/cocoa. h>

 

@ Interface photo: nsobject {

Nsstring * Caption;

Nsstring * photographer;

}

@ End

 

First, weCocoa. hImport. Most of the basic classes of cocoa applications do this.# ImportMacro commands automatically prevent the same file from being contained multiple times.

 

@ InterfaceThe symbol indicates that this is the declaration of the photo class. The colon specifies the parent class. In the preceding example, the parent class is nsobject.

 

There are two variables in the Large arc:CaptionAndPhotographer. Both areNsstringType. Of course, they can also be any other type, including the ID type.

 

Last@ EndEnd the entire statement.

 

Add Method

Let's add some getters for the member variables:

 

# Import <Cocoa/cocoa. h>

 

@ Interface photo: nsobject {

Nsstring * Caption;

Nsstring * photographer;

}

 

-Caption;

-Photographer;

 

@ End

 

Do not forget that the get prefix is not required for the objective-C method. A single small horizontal bar indicates that it is an instance method. If it is a plus sign, it indicates that it is a class method.

 

The return type of the default method of the compiler is ID. The default type of parameters of all methods is also ID type. Therefore, the above Code is technically correct. But it is rarely used. Let's add the return type to it:

 

# Import <Cocoa/cocoa. h>

 

@ Interface photo: nsobject {

Nsstring * Caption;

Nsstring * photographer;

}

 

-(Nsstring *) caption;

-(Nsstring *) photographer;

 

@ End

 

Next we will add setters:

 

# Import <Cocoa/cocoa. h>

 

@ Interface photo: nsobject {

Nsstring * Caption;

Nsstring * photographer;

}

-(Nsstring *) caption;

-(Nsstring *) photographer;

 

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

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

 

@ End

 

Setters does not need to return any value, so we specify its typeVoid.

 

6

 

ClassImplementation

We create a class implementation by implementing getters:

 

# Import "photo. H"

 

@ Implementation photo

 

-(Nsstring *) caption {

Return Caption;

}

 

-(Nsstring *) photographer {

Return photographer;

}

 

@ End

 

This part of the code consists@ ImplementationAdd the class name and start@ EndEnd. Just like the Interface Definition of a class, all methods are the same as those in the interface definition. All objects must be defined and implemented.

 

If we have written code before, getters in objective-C looks similar to others. So here we will introduce setters, which requires some instructions.

 

-(Void) setcaption: (nsstring *) Input

{

;

Caption = [input retain];

}

 

-(Void) setphotographer: (nsstring *) Input

{

[Photographer autorelease];

Photographer = [input retain];

}

 

Each setter processes two variables. The first is the application of the existing object. The second is the new input object. In a development environment that supports garbage collection, we only need to directly add new values:

 

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

Caption = input;

}

 

But if we cannot use the garbage collection mechanism, we need to firstRetainThe old object, and thenRetainNew object.

 

There are two ways to release a reference object:ReleaseAndAutorelease. StandardReleaseWill Directly Delete the reference.AutoreleaseThe method will go at some time in the futureReleaseIt. It will undoubtedly exist before it declares that the cycle is over. In this example, the photographer object in setphotographer will be released at the end of the function.

 

Using autorelease in setter is safe, because the new object and the old object may be the same object and may point to the same object. For an object we are about to retain, we should not immediately release it.

 

This may seem confusing now, but as we learn, we will be more and more able to understand it. Now we don't need to fully understand it.

 

 

Initialization

We can create an initialization method to assign an initial value to the member variable of the class instance:

 

-(ID) Init

{

If (Self = [Super init])

{

[Self setcaption: @ "Default caption"];

[Self setphotographer: @ "Default photographer"];

}

Return self;

}

 

The above Code seems useless, although the second line of code seems useless. This is a single equal sign, that is[Super init]The value is assignedSelf.

 

It basically calls the parent class to implement its initialization. This if code segment verifies whether Initialization is successful before setting the default value.

 

 

Release resourcesDealloc

ThisDeallocThe method is called when an object is to be deleted from the content. This is the best time to release member variables in the subclass:

 

-(Void) dealloc

{

;

[Photographer release];

[Super dealloc];

}

 

In the first two rows, we sent the release notification to two member variables. We should not use autorelease here. It is faster to use standard release.

 

[Super dealloc]; Very important. We must send a message so that the parent class can clear itself. If this is not done, the object is not cleared, and memory leakage exists.

 

Dealloc is not called in the garbage collection mechanism. Instead, we need to implementFinalizeMethod.

 

7

 

More on Memory Management

The objective-C memory management system is based on reference records. All we need to care about is tracking our reference and whether the memory is actually released at runtime.

 

In the simplest terms, when alloc is an object, it should be retained at some time. Every time we call alloc or retain, we must call release.

 

/////... Figure ....

This is the reference of the numerator theory. However, in practice, we only need to create an object in two cases:

 

1. Become a member variable of a class

2. Only temporarily used in one function

 

In more cases, the setter of a member variable should only autorelease the old object, and then retain the new object. We only need to call release in dealloc.

 

So what really needs to be done is to manage local references within the function. The only principle is: if we use alloc or copy an object, we need to release or autorelease it at the end of the function. If it is created in another way, it doesn't matter.

 

Here is an example of managing Member objects:

 

-(Void) settotalamount: (nsnumber *) Input

{

[Totalamount autorelease];

Totalamount = [input retain];

}

 

-(Void) dealloc

{

[Totalamount release];

[Super dealloc];

}

 

Here is an example of local reference. We only need to release the object we created with alloc:

 

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

Nsnumber * value2 = [nsnumber numberwithfloat: 14.78];

 

// Only release value1, not value2

[Value1 release];

 

Here is an example of using a local reference object to set a member variable:

 

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

[Self settotal: value1];

 

Nsnumber * value2 = [nsnumber numberwithfloat: 14.78];

[Self settotal: value2];

 

[Value1 release];

 

Note that managing local references is actually the same. Whether or not you have set it to a member variable. We do not need to consider the internal implementation of setters.

 

If we have a good understanding of this, we have basically understood 80% of objective-C memory management.

 

 

8

Logging

In objective-C, it is very easy to write a diary to the console. In factNslog ()C LanguagePrintf ()The two functions are almost identical, except for the nslog% @"To obtain the object.

 

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

We can log an object to the console. The nslog function callsDescriptionAnd print the returned nsstring. We can override the description method in our class so that we can get a custom string.

 

9

AttributeProperties

Previously we wroteCaptionAndAuthorYou can note that the code is very concise and can be abstracted.

 

Attributes are a new feature in objective-C. It allows us to automatically generate accessors, and has some other advantages. We can convert the above photo class into attributes for implementation:

 

The previous implementation of the class above is as follows:

 

# Import <Cocoa/cocoa. h>

 

@ Interface photo: nsobject {

Nsstring * Caption;

Nsstring * photographer;

}

-(Nsstring *) caption;

-(Nsstring *) photographer;

 

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

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

 

@ End

 

We assume that the attribute is implemented as follows:

 

# Import <Cocoa/cocoa. h>

 

@ Interface photo: nsobject {

Nsstring * Caption;

Nsstring * photographer;

}

@ Property (retain) nsstring * Caption;

@ Property (retain) nsstring * photographer;

 

@ End

 

@ PropertyIs the Compilation instruction for declaring attributes in objective-C. The "retain" in the brackets specifies the object that the setter needs to retain input. The other part of this line specifies the attribute type and name.

 

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

 

@ SynthesizeThe command automatically generates our setters and getters. Therefore, we only need to implement the dealloc method of the class.

 

Accessors are generated only when they are not. So you can safely and boldly use @ synthesize to specify attributes. You can also implement your own getter and setter at will. The compiler does not find any method by itself.

 

There are other options for Attribute declaration, but we will introduce them again next time.

 

 

10

Calling methods on Nil

In objective-C, the NIL object is designed to be associated with null pointers. Their difference is that nil is an object, while null is only a value. In addition, the NIL call method does not generate crash or throw an exception.

 

This technology is used by the framework in many different ways. The most important thing is that we do not need to check whether the object is nil before calling the method. If we call a nil object method with a returned value, we will get a nil return value.

 

We can use the NIL object to make our dealloc function look more handsome:

 

-(Void) dealloc

{

Self. Caption = nil;

Self. Photographer = nil;

[Super dealloc];

}

 

This can be done because we set the NIL object to a member variable, and setter will retain nil object (of course nil object will not do anything at this time) and then release the old object. It is better to release objects in this way, because in this case, the member variables do not even have the opportunity to point to random data. In other ways, the opportunity to point to random data is inevitable.

 

Note the self. <var> syntax we call, which means we are using setter and will not cause any memory problems. If we set the value directly, there will be a memory overflow:

 

// Incorrect. causes a memory leak. 

// Use self. caption to go through setter 

Caption = nil;

 

11

Categories

Categories is one of the most commonly used functions in objective-C. Basically, category allows us to add methods to existing classes without adding a subclass. You do not need to know its internal implementation.

 

This is very effective if we want to add methods of classes that come with a framework. If we want to add a method in nsstring of our program project, we can use category. You do not even need to implement an nsstring subclass.

 

For example, if we want to add a method in nsstring to determine whether it is a URL, we can do this:

 

# Import <Cocoa/cocoa. h>

 

@ Interface nsstring (utilities)

-(Bool) isurl;

@ End

 

This is very similar to the class definition. The difference is that the category does not have a parent class, and the category name must be included in the brackets. The name can be retrieved at will, but it is a habit of calling a method that makes people better understand some functional methods in category.

 

Here is the specific implementation. However, note that this is not a good way to judge the URL. We mainly aim to understand the concept of category as a whole.

 

# Import NSString-Utilities.h"

 

@ Implementation nsstring (utilities)

 

-(Bool) isurl

{

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

Return yes;

Else

Return no;

}

 

@ End

 

Now we can call this method in any nsstring class object. The following code prints "string1 is a URL" on the console ":

 

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

Nsstring * string2 = @ "Pixar ";

 

If ([string1 isurl])

Nslog (@ "string1 is a URL ");

 

If ([string2 isurl])

Nslog (@ "string2 is a URL ");

 

Unlike subclass, category cannot add member variables. We can also use category to override the existing methods of the class, but this requires great caution.

 

Remember, when we modify a class through category, it takes effect for all objects of this class in the application.

 

AfterNote

Here is a rough description of the comparison between objective-C and objective-C. Objective-C is easy to use. There is no special syntax to learn. In addition, some concepts are repeatedly used in objective-C.

 

Example of this article: http://www.cocoadev.cn/sourcecode.asp

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.