Go to objective-C

Source: Internet
Author: User

From: http://tiny4cocoa.com/doc/xcode-doc/learn-objective-c

 

Objective-C is a simple computer language designed to support real object-oriented programming. Objective-C extends the Standard ansi c language by providing class definitions, methods, and attribute syntaxes, as well as other structures that can improve the dynamic scalability of classes. Class syntax and design is mainly based on smalltalk, one of the earliest object-oriented programming languages.

If you have used other object-oriented programming languages before, the following information can help you learn the basic syntax of objective-C. Many traditional object-oriented concepts, such as encapsulation, inheritance, and polymorphism, are embodied in objective-C. There are some important differences here, but these differences will be shown in this article, and if you need more details, they will exist.

If you have never compiled programs using any programming language, you should at least have a basic understanding of related concepts before you start. Object use and object architecture are the basis of iPhone programming. It is very important to understand how they interact to create your program. For more information about object-oriented programming, see use objective-C for object-oriented programming. In addition, refer to the basic cocoa guide to get information about the object-oriented design patterns in cocoa.

For more details about objective-C and syntax, see objective-C 2.0.

Objective-C: superset of C

Objective-C is a superset of the ansi c programming language and supports the basic syntax of C. In C code, you define the header file and the source code file, and separate the public declaration from the code implementation details. The object names used by the objective-C header file are listed in Table 1.

Table 1 objective-C code file extension

Extension Content type
. H Header file. The header file contains class, type, function, and constant declarations.
. M Source code file. This is a typical source code file extension that can contain objective-C and C code.
. Mm Source code file. Source code files with such extensions can contain not only objective-C and C code, but also C ++ code. This extension is used only when your objective-C code does need to use C ++ classes or features.

When you need to include header files in the source code, you can use the standard # include compilation option, but objective-C provides a better method. The # import option and # include option are identical, but they ensure that the same file is only contained once. Objective-C examples and documents tend to use # import, and your code should also be like this.

String

As a superset of C language, objective-C supports the conventions on C language strings. That is to say, a single character is enclosed by single quotes, and a string is enclosed by double quotes. However, most objective-C normally do not use C-style strings. Conversely, most frameworks pass strings to nsstring objects. The nsstring class provides string class packaging, including all the advantages you want, including the built-in memory management mechanism for saving strings of any length, support for Unicode, printf style formatting tools, and so on. Because such strings are frequently used, objective-C provides a mnemonic to easily create an nsstring object from a constant value. All you need to do is place a @ symbol before a regular double quotation mark string, as shown in the following example:

Nsstring * mystring = @ "my string/N"; nsstring * anotherstring = [nsstring stringwithformat: @ "% d % s", 1, @ "string"]; // create an objective-C string from a C string nsstring * fromcstring = [nsstring stringwithcstring: "a c string" encoding: nsasciistringencoding];
Class

Like all other object-oriented languages, classes are basic structures used by objective-C to encapsulate data and manipulate data. An object is an instance during the running of a class. It contains the memory copies of the instance variables declared by the class and pointers of class members. The class type description of objective-C consists of two parts: interface and implementation. The Interface part includes the class declaration, instance variable definition, and class-related methods. The implementation part contains the actual code of the class method. Figure 1 shows the syntax for declaring a class called myclass, which inherits from the nsobject base class. The class declaration always starts with the @ interface compilation option and ends with the @ end compilation option. After the class name (separated by a colon) is the name of the parent class. The instance (or member) variables of the class are declared in the code block contained in braces. The instance variable block is followed by a list of methods declared by the class. Each instance variable and method declaration end with a semicolon.

Figure 1 class declaration

List 1 shows the implementation of the myclass class in the previous example. Similar to the class declaration, the class implementation location is determined by two compilation options, @ implementation and @ end. These options provide the compiler with the required range information to associate the method with the corresponding class. Therefore, the method definition matches the Declaration corresponding to the interface, but there is only one more code block.

List 1 Implementation

@implementation MyClass    - (id)initWithString:(NSString *) aName{    if (self = [super init]) {        count count = 0;        data = nil;        name = [aName copy];        return self;    }}  + (MyClass *)createMyClassWithString: (NSString *) aName{    return [[[self alloc] initWithString:aName] autorelease];}@end

Note: although the previous class only declares methods, the class can declare attributes. For more information about attributes, see "attributes ".

 

When saving objects with variables, always use the pointer type. Objective-C supports two types of objects contained in variables: strong and weak. The variable type declaration of a strongly typed pointer contains the class name. Weak type pointer uses ID as the object type. Weak type pointers are often used in the collection of classes. The exact type of objects in the collection can be unknown. If you use a strong type language, you may think that using weak type variables may cause problems, but they actually give the objective-C program great flexibility and make it more powerful.

The following example shows the strongly typed and weak declared variables of the myclass class:

MyClass*  myObject1;    // Strong typingid        myObject2;    // Weak typing

 

Method

Classes in objective-C can declare two types of Methods: instance methods and class methods. An instance method is a method that is executed within the scope of a specific instance of the class. That is to say, before you call an instance method, you must first create an instance of the class. Compared with the class method, that is, you do not need to create an instance.

A Method Declaration includes a method type identifier, a return value type, one or more method identity keywords, parameter types, and name information. Figure 2 shows the insertobject: atindex: instance method declaration. The Declaration starts with a minus sign (-), which indicates that this is an instance method. The actual method name (insertobject: atindex :) is the key cascade of all methods, including colons. The colon indicates the appearance of parameters. If the method does not have a parameter, You can omit the colon next to the first (and only) method identifier keyword. In this example, this method has two parameters.

Figure 2 method declaration syntax

When you want to call a method, you can transmit the message to the corresponding object. The message here is the method identifier and the parameter information passed to the method. All messages sent to an object are dynamically distributed, which facilitates the implementation of objective-C multi-state behavior. That is to say, if the subclass defines a method with the same identifier as the parent class, the subclass receives the message first, and then can choose to forward the message (or not) to the parent class.

The message is enclosed in brackets ([and. In the middle of the brackets, the recipient is on the left, and the message (including any parameters required by the message) is on the right. For example, to pass the message insertobject: atindex: Message to the myarray variable, you need to use the following syntax:

[myArray insertObject:anObj atIndex:0];

To avoid declaring too many local variables to save temporary results, objective-C allows you to use nested messages. The returned values of each nested message can be used as parameters or targets of other messages. For example, you can use any message that obtains this value to replace any variable in the preceding example. Therefore, if you have another object named myappobject with a method, you can access the array object and insert the object into an array, you can write the previous example as follows:

[[myAppObject getArray] insertObject:[myAppObject getObjectToInsert] atIndex:0];

Although the previous example is to pass messages to an instance of a class, you can also pass messages to the class itself. When sending messages to a class, the method you specify must be defined as a class method, rather than an instance method. You can think that the class method is a bit like the static member in the C ++ class (but not exactly the same ).

 

A typical use of a class method is to create a factory method for a new class instance, or to share information related to the class. The class method declaration syntax is almost the same as that of the instance method, with only a small difference. Unlike the instance method that uses the minus sign as the method type identifier, the class method uses the plus sign (+ ).

The following example demonstrates how a class method acts as a class factory method. Here, arraywithcapacity is the class method of the nsmutablearray class. It allocates content to the new instance of the class and initializes it, and then returns it to you.

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];
Attribute

Attribute is a convenient way to replace the declared access method. Attribute does not create a new instance variable in your class declaration. They are just shorthand for defining methods to access existing instance variables. Class that exposes instance variables. You can use the attribute mark to replace the getter and setter syntaxes. Classes can also use attributes to expose some "virtual" instance variables, which are the results of dynamic computing of some data, rather than actually saved in instance variables.

In fact, attributes save a lot of unnecessary code you need. Because most access methods are implemented in a similar way, attributes avoid providing different getter and setter requirements for each instance variable exposed by the class. Instead, you use the attribute declaration to specify the behavior you want, and then combine the actual getter and setter methods based on the declaration during compilation.

The attribute declaration should be placed in the method declaration of the class interface. The basic definition uses the @ property compilation option, followed by the type information and attribute name. You can also use custom options to configure attributes, which determines the behavior of the access method. The following example shows some simple attribute declarations:

@property BOOL flag;@property (copy) NSString* nameObject;  // Copy the object during assignment.@property (readonly) UIView* rootView;  // Create only a getter method.

Another advantage of using properties is that you can use the dot syntax when accessing them in code, as shown in the following example:

myObject.flag = YES;CGRect   viewFrame = myObject.rootView.frame;

Although the objects and attribute names in the preceding example are intentionally obtained, they show the flexibility of attributes. The point syntax actually hides the corresponding method call. Each readable attribute is supported by a method with the same name as the attribute. Each writable attribute is supported by an additional method called "set attribute name". The first letter of the attribute name must be capitalized. (These methods are the actual implementation of attributes, and also the reason you can declare an attribute declaration without any instance variables .) If you use a method to replace the attributes in the previous code, you need the following code:

[myObject setFlag:YES];CGRect   viewFrame = [[myObject rootView] frame];

For more information about how to declare attributes, see the attributes chapter of objective-C 2.0 programming language.

 

Protocols and Proxies

The Protocol declares methods that can be implemented by any class. Protocols are not those classes. They define only one interface, and other objects are responsible for implementation. The method in the Protocol is called compliance.

In iPhone OS, protocols are often used to implement delegate objects. A delegated object acts as another object. The best way to understand the protocol and delegate and object is to look at an example.

The uiapplication class implements the behavior required by a program. To receive simple messages in the current state of the program, you do not need to create a subclass of uiapplication. Otherwise, the uiapplication class distributes these notification messages by calling the specified method of the delegate object. Objects implementing the uiapplicationdelegate method can receive such notifications and respond accordingly.

The Declaration of the Protocol is similar to the declaration of the class interface, but the Protocol does not have a parent class, and they do not define any instance variables. The following example shows a protocol statement with a method:

@protocol MyProtocol- (void)myProtocolMethod;@end

In most delegated protocols, using a certain protocol is just a simple method to implement the Protocol definition. Some protocols require you to explicitly indicate that you support this Protocol. The Protocol can specify required or optional methods. During your in-depth development, you should spend some time learning the protocols and their usage. Please read the objective-C 2.0 programming language protocol section.

More information

The preceding information is used to give you a basic understanding of objective-C. The language features mentioned in this article can be found when you read the complete documentation. But this language does not only have these features, so it is best to read the objective-C 2.0 programming language carefully.

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.