IPhone Development Series (III)-objective-C language Introduction

Source: Internet
Author: User

I have translated the technical information of the apple Dev center and slightly modified it.

Reprinted please indicate the source: http://blog.csdn.net/zhyzh2046/

Learning objective-C: basic readingObjective-C is a simple computer language that supports complex Object-Oriented Programming in Nantong. Objective-C is extended from the Standard ansi c language and provides syntax for defining classes, methods, and attributes, as well as other structures to facilitate dynamic extension of classes. Class syntax and design is based on the first object-oriented programming language smalltalk. If you have experience using object-oriented languages, the following information will help you learn the basic syntax of objective-C. Many traditional object-oriented concepts, such as encapsulation, inheritance, and polymorphism, will appear in objective-C. However, there will be some important differences, but this article will explain these differences and provide more detailed information. If you have never used an object-oriented language, you must at least understand the relevant concepts before you start. The use of objects and object-oriented structures is the foundation for designing iPhone programs, and understanding how they interact is a necessary condition for creating programs. An overview of object-oriented concepts is introduced in Object-Oriented Programming Using objective-C. For more information and syntax about objective-C, see objective-C program design.

Objective-C: superset of C Language

Objective-C is an ANSI superset of C language and supports the same basic syntax. Similar to the C language, objective-C also defines header files and source files to separate common declarations and implementations. The file extensions used by the objective-C header file are listed in Table 1.

 

Table 1 Object-C source code file extensions
Extension Code Type
. H Header file. The header file contains the declaration of classes, types, functions, and constants.
. M Source file. This is a typical extension of the source file. It can contain C code and objective-C code.
. Mm Source file. In addition to C code and objective-C code, such source files can also contain c ++ code. This extension can only be used when you actually reference the C ++ class or the objective-C function.

 

When a header file contains a header file, you can use the standard # include precompilation command, but objective-C provides a better method. # The import command is the same as the # include command, except that it can ensure that the same file will never be referenced multiple times. We recommend that you use # import for objective-C examples and documents, as should your own code.

Strings

As the superset of C, objective-C has the same conventions as C when specifying strings. In other words, a single character is enclosed by single quotes, and strings are enclosed by double quotes. However, most objective-C frameworks often do not use C-style strings. Instead, most frameworks encapsulate strings in an nsstring object.

The nsstring class is the object carrier of a string. It has all the expected advantages, including the built-in memory management for processing strings of any length, support for Unicode and printf formatting, and so on. However, because some strings are frequently used, objective-C provides a stenographer to create an nsstring object from a constant. Using stenographer, all you need to do is add a @ symbol before a string contained in a normal double quotation mark, as shown in the following example:

Nsstring * mystring = @ "my string ";
Nsstring * anotherstring = [nsstring stringwithformat: @ "% d % s", 1, @ "string"];

// Create an objective-C string from a C string
// Create an objective-C string from the C string
Nsstring * fromcstring = [nsstring stringwithcstring: "a c string" encoding: nsasciistringencoding];

Classes
Class

Like most other object-oriented languages, classes in objective-C are a basic structure that encapsulates some data and the actions that manipulate the data. An object is an instance of the class runtime, including copying the member variables declared in the class and the class method pointers in the memory.

Creating a class in objective-C requires two completely different parts: interfaces and implementations. The Interface contains the declaration of classes. It also defines member variables and methods associated with classes. The implementation part contains the actual implementation code of the class method. Figure 1 shows the syntax for declaring a class called myclass, which inherits the nsobject base class. The class Declaration starts with the @ interface precompiled command and ends with the @ end command. A Class Name (separated by a colon) is the name of the parent class. The member variables of the class are declared ({And}) in the Code contained in braces }). The code block after the member variable is a list of methods declared by the class. Each member variable and method declaration must end with a semicolon.
Figure 1 class declaration

Figure 2 shows the implementation of myclass in the previous example. Like the declaration of a class, the implementation of the class is indicated by two pre-compiled commands-here is @ implementation and @ end. These commands define the range information and tell the compiler to associate the attached methods with related classes. Therefore, the method definition must match the declaration in the interface, except the code block.

Figure 2 Implementation

Note: although in the above example, the declaration part of the class only declares some methods, the class can declare attributes here. For more information about attributes, see "attributes.

When using variables to store objects, the pointer type is often used. In objective-C, both strong and weak variables can save objects. A variable with a strong type pointer must contain the class name during declaration. Collection classes often use weak type pointers, because they may not know the type of objects in the collection. If you are used to strong-type programming languages, you may think that the use of weak type variables will cause problems, but in fact, it will bring great convenience when using objective-C programming, at the same time, it will bring better scalability.

The following example demonstrates the declaration of strong and weak type variables of the myclass class:

Myclass * myobject1; // strongly typed
Id myobject2; // weak type

Methods
Method
 

Objective-classes in C can declare two methods: instance methods and class methods. The executor of the instance method must be a specific instance of the class. In other words, you must create a class instance before calling the instance method, and then use this instance to call the actual method. In contrast, you do not need to create a class instance for the class method, and a detailed explanation will be provided later.

A Method Declaration consists of a method type identifier, a return type, one or more signature keywords, parameter names, and type information. Figure 3 shows an instance method of insertobject: atindex. A subtraction symbol (-) is added before the method declaration, which indicates that this method is an instance method. The actual method name (insertobject: atindex :) is concatenated by all the signature keywords, including the colon character. The colon indicates the existence of the parameter. If the method has no parameters, the colon can be ignored after the first (unique) signature is key. In this example, the method contains two parameters. Figure 3 declaration method syntax when a method is called, the corresponding object must be notified through "messaging. The message in this example is the parameter information required by the method name and method. All messages sent to an object are dynamically sent. Therefore, this is conducive to the polymorphism of objective-C. In other words, if the subclass defines a method with the same name as the parent class, the subclass receives the message first, and then can choose whether to forward the message to its parent class.

Messages are placed in square brackets ([and. In square brackets, the message receiving object is placed on the left, and the message (and any parameters required by the message) is placed on the right. For example, to send an insertobject: atindex: Message to the myarray object, the syntax is as follows:

[Myarray insertobject: anobj atindex: 0]; To avoid declaring a large number of local variables to store temporary data, objective-C supports nested messages. The returned values of each nested message can be used as parameters or targets of another message. For example, any variable in the above example can be replaced with a message to get the value. Therefore, if there is another object myappobject, its method can access the array object, and there is another array object, you can write the above example as follows:

[[Myappobject getarray] insertobject: [myappobject getobjecttoinsert] atindex: 0]; although the previous example is to send a message to a class instance, you can also send a message to the class itself. When sending a message to a class, the called method must be defined as a class method instead of an instance method. It can be considered that the class method is similar to the static member method of the class in C ++ language (but not completely similar ). The typical usage of class methods is to create a new instance of the class as a factory method, or to access shared information related to the class. The definition Syntax of a class method is exactly the same as that of an instance method. The class method uses the addition symbol (+) instead of the subtraction symbol as the type identifier of the method. The example below demonstrates the use of the Class method, which serves as the factory method of the class. Here, arraywithcapacity: The method is the nsmutablearray class method, which applies for and initializes a new class instance and returns it.

Nsmutablearray * myarray = nil; // NIL is essentially the same as null

// Create a new array and assign it to the myarray variable
Myarray = [nsmutablearray arraywithcapacity: 0];

 

Properties AttributeAn attribute is a convenient symbol used to replace an access method (accessor methods ). The attribute does not create a new member variable in the class declaration. They only specify shortcuts for defining methods used to access existing variables. Class can use Attribute tags to publish member variables, rather than using the getter and setter methods. Class can also use attributes to publish virtual member variables-it is a part of the dynamic computing data and is not actually stored in member variables.

Actually, the use of attributes reduces the amount of redundant code. Most access methods should be implemented in a similar way. Using attributes does not have to provide completely different getter and setter methods for each member variable. Instead, you can use the attribute declaration to specify specific actions. during compilation, the actual getter and setter methods will be merged based on the declaration.

Because the attribute Declaration creates an actual method, it can be defined in the class interface together with the method declaration. The basic definition uses the @ property pre-compilation command, followed by the property type information and name. You can use custom options to configure attributes, which define the behavior of the access method. The following example shows some simple type declarations:

@ Property bool flag;
@ Property (copy) nsstring * nameobject; // copy an object during the value assignment process
@ Property (readonly) uiview * rootview; // only create the getter Method

Another benefit of attributes is that you can use the dot syntax to access them in the code, as shown below:

Myobject. Flag = yes;
Cgrect viewframe = myobject. rootview. frame;
 

Although the names of objects and properties in the above example are pretentious, they demonstrate the flexibility of attributes. Point syntax effectively shields calls to a series of related methods. Each readable attribute is supported by methods with the same name. Each writable attribute is set by the additional Method Propertyname: Yes. Here, the first letter of the attribute name is capitalized. (These methods are the actual implementation of attributes, and they can also include attribute definitions in classes that are not supported by member variables .) You do not need to use attributes to implement the functions completed by the above code. You need to write the following code:

[Myobject setflag: Yes];
Cgrect viewframe = [[myobject rootview] frame];
 

For more information about how to declare attributes in a class, see the "attributes" section in objective-C programming.

Protocols and delegates Protocols and Proxies

 

The method declared by the Protocol can be implemented by any class. The Protocol is not the class itself. They only define interfaces that are implemented by other objects. When implementing the Protocol method in your own class, your class complies with this Protocol.

In iPhone OS, protocols are often used as proxy objects. A proxy object is an object that can represent other objects or cooperate with other objects. The best way to learn how protocols, proxies, and other objects interact with each other is to learn from the example.

The uiapplication class implements the functions required by the application. Instead of forcibly inheriting the uiapplication class to receive notifications in the current state of a simple application, the uiapplication class calls the method assigned to the proxy object to distribute these notifications. Objects that implement the uiapplicationdelegate protocol can receive these notifications and provide appropriate responses.

The declaration of a protocol is similar to the declaration of a class interface. The Protocol does not have a parent class and cannot define member variables. The following example demonstrates the Protocol declaration with only one method:

@ Protocol myprotocol
-(Void) myprotocolmethod;
@ End

 

In many proxy protocols, the Protocol only implements the methods defined in the Protocol. Some protocols need to explicitly declare the supported protocols, but now it is sufficient to implement only the methods. However, if you want to apply more to your development, you should spend more time learning protocols and their usage methods, you can refer to the "protocol" section in objective-C programming.

 

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.