Introduction to OBJECTIVE-C (2) Class declarations and definitions

Source: Internet
Author: User
Tags processing instruction

Compile and process commands 

Since Objective-C is an object-oriented programming language, it should support reusable data and function encapsulation bodies, that is, classes.

A class is a product developed on the basis of a struct. A struct can only process data. Adding a function for processing data on the struct constitutes the concept of a class. Class enables the program to always provide secure calls to specially processed functions, so that a series of functions can be used as a sub-system safely and repeatedly.

Like a struct, classes must be declared before they are used. However, Objective-C does not provide special keywords or syntax for declaring classes as other object-oriented languages do, it is implemented by compiling and processing commands. The feature is that all class declaration statements must start with the @ symbol.

The compilation and processing commands of class declaration start with @ interface and end with @ end. The code between them is the definition of Class variables and the declaration of methods. Class declarations and definitions are more complex than those in other languages, which can confuse those who are learning Objective-C at the beginning (to be precise, other languages such as Java only need to define classes instead of declarations, and Objective-C needs to be declared and then defined ).

@ Interface Class Name: parent class name {
Instance variable definition
...
}
Method Declaration
@end

 

This is the syntax structure of the Objective-C class declaration.Instance variables are used inside the class. They are similar to the member variables of the struct, but instance variables cannot be used outside the class, in principle, it can only be used by internal methods of the class (of course, only in principle ). Class can have no instance variables.{}Can be omitted.

The class method (note the difference with the class method) is the exclusive class method, the difference with the ordinary function is: the class method can operate the instance variable inside the class.

Next to the class name is the parent class name, that is, you can specify the parent class of the class to constitute inheritance. Inheritance enables the class to inherit and use the functions of the parent class, and only defines the functions that the parent class does not have. For example, the parent class is an abstract mammal class. If a cat class is defined, it can inherit the parent class of a mammal, in cat categories, only the unique functions of cat differences and common mammals can be defined.

The parent class can be left unspecified. In this case, the compiler will provide a default class for the class, that is, the root class.

The root class of Objective-C varies with the specific compiler. The GCC compiler is an Object, while the Cocoa compiling environment of Mac OS X is NSObject, unless you do not specify the parent class when developing the root class, the root class provided by the system is generally used as the parent class. When developing the root class only, the class can be defined as follows (no parent class ):

@ Interface Class Name
{
Instance variable Declaration
...
}
Class method declaration
@end

 

Why must all classes inherit from a common root class? This is because the root class provides some basic functions required for normal class operations, such as the acquisition and release of memory, if there is no root class, all the classes must complete these basic tasks by themselves, which will make the classes very complex and not focus on specific services (which will be described later ).

There is no difference between the declaration of instance variables in the class and the declaration of variables in the common C language, but the Declaration of class methods is very different. The syntax is as follows:

-(Return Value Type)Method Name :Temporary parameter Column...;

First, the leftmost minus sign indicates that the method is an instance method of the class. If it is a plus sign, it indicates that the method is a class method. Note: when defining a class, you can use the minus sign (Instance) before the method. The class method can be called directly without generating an instance. The differences between instance methods and class methods are described in detail later.

Second, the return value type should be placed in (). If the function requires a parameter, the parameter type should also be placed in (), followed by the parameter name. If there are multiple parameters, separated by commas.

The default Return Value Type of C-language functions is int type, and an id type object type is added to Objective-C as the return value type of the default function. Although the return value can be unspecified, it is generally not recommended to do so. If no return value is returned, use (void) to specify it.

@interface Test : Object
- (void)method;
@end

In this Test class declaration, a method with no return value and no parameters is declared. The naming rules for classes, methods, and variables are the same as those in the C language and start with a letter or underscore. However, the first letter of the class name is used to be in upper case, and the method name is in lower case.

By now, the class declaration has been completed, but the method only declares the name and type. How to Write the specific implementation code? In fact, Objective-C completely separates the class declaration and definition. In the class declaration, only instance variables and method names and types can be defined, the specific implementation should be carried out in the @ implementation compilation and processing instruction.

@ Implementation Class Name
Instance method definition
...
@ End

@ Implementation: the Compilation instruction defines the methods declared in @ interface. The declared methods must be defined here.

 

Class instantiation

 

Classes are declared and defined, but cannot be used directly. Before using classes, you must allocate specific memory areas and perform proper initialization. Allocate a memory according to the class declaration. This process is called Instantiation, and the memory allocated is called an instance or object.

C ++ or Java provides us with the new operator, which can automatically generate instances from classes and complete initialization, the Objective-C instantiation must also be completed by the class itself (that is, the class must provide its own method of Instantiation ). Instantiation requires investigating the size of the generated Object and applying for memory to complete complex initialization. These tasks are too difficult for common users. Fortunately, the compiling environment provides us with the root class (Object) to help complete these functions, which is why all classes must inherit from the root class (otherwise the instantiation method should be written by themselves ).

In the root class Object, the class method alloc is defined for instantiating the root class and inheriting the class from the root class. The general instance method must have an instance before it can be called, but the class method, it can also be used without instances. Therefore, although the class method alloc does not have an instance, it can also be called normally. Since alloc is a class method used to generate an instance, it is also often called a factory method.

+ Alloc;

This is the declaration of alloc in the Object, starting with "+", indicating that it is a class method. The default return value is id type and there is no parameter.

Id type indicates the generalized type of an object. All types of objects can be placed in id type objects.

Next, we need to call the alloc class method to generate an instance. But how can we write it? If you are familiar with C ++, you may first consider the following call method:

Id obj =Class Name. Alloc ();

Unfortunately, this method isErrorUnlike most object-oriented languages, Objective-C has its own unique call method:

[Class Name Class Method Name:Parameter Sequence...]

 

When you call an instance method, replace the class name with the instance name. [] is called a message in Objective-C, because in Objective-C, when an object calls a method, instead of calling it directly, it sends a specific message to the object. After the object receives the message, it starts the corresponding method based on the message content, although this method brings flexibility to the program, it consumes more time than the C language call method, because it takes time to search for a specific method and start the program.

#import <stdio.h>
#import <objc/Object.h>

@interface Test : Object
- (void)method;
@end

@implementation Test
- (void)method {
printf("Kitty on your lap\n");
}
@end

int main() {
id obj = [Test alloc];
[obj method];

return 0;
}

 

The above program is a simple but complete Objective-C class instance example. @ interface completes the class declaration and inherits from the root class Object. @ Implementation defines the class and defines the implementation method of the method.

After the class declaration and definition are ready, in the main function, first define the Object variable obj of the id type, and then call the class method alloc of the parent class Object of the Test class to generate an instance, finally, call the instance method of the Instance obj to print the output.

In addition, if you do not define the obj variable (or the Test instance is used only once here), you can also write the following statement:

[[Test alloc] method]

Note: like the program fragment above, although there is no requirement on the class declaration and the specific location of the definition, we are used to putting the class declaration in the header file, the class is defined in the same name as the class name. m file.

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.