Objective-C 2.0-(Article 1-5)-familiar with objective-C

Source: Internet
Author: User

Objective-C adds the object-oriented Feature Based on the C language through a new set of syntax. The OC syntax frequently uses braces ([]) and does not limit writing very long method names, which often makes many people think the language is lengthy. The code written in this way is very readable, but C ++ and Java programmers are not very comfortable with it.

OC linguistics is very fast, but there are a lot of subtle details to note, and there are many characteristics that are easy to ignore. On the other hand, some developers do not fully understand or abuse some features, which makes it difficult to maintain and debug the written code. This chapter describes the basic knowledge and specific topics about the language and related architecture of subsequent chapters.

Article 1st: understanding the origin of OC Language

OC is similar to object-oriented languages such as C ++ and Java, but there are many differences. If another object-oriented language is used, many paradigms and templates used by OC can be understood. However, the syntax may seem unfamiliar, because OC uses the messaging structure instead of function calling ). OC evolved from smalltalk. The latter is the originator of the messaging language. The difference between messages and function calls looks like this:

//Messaging (OC)Object *obj = [Object new];[obj perfromWith:parameter1 and:parameter2];//Function calling(C++)Object *obj = new object;obj->perform(parameter1,parameter2);

The key difference lies in the use of the message structure language. The code to be executed during running is determined by the running environment, while the language to be called by the function is determined by the compiler. If the function called in the sample code is polymorphism, you need to follow the "virtual table" to find the function to be executed at runtime. The message structure language always finds the method to be executed at runtime, regardless of the polymorphism. In fact, the compiler does not even care about the type of objects that receive messages. Objects that receive messages must also be processed at runtime. The process is called "dynamic binding" (dynamic binding). For details, see 11th.

The important work of OC is done by the runtime component rather than the compiler. All data structures and functions required to use the object-oriented feature of OC are in runtime components. For example, the runtime component contains all the memory management methods. The runtime component is essentially a "dynamic library" linked to the Code Compiled by the developer. Its code can bond all programs written by the developer. In this way, you only need to update the runtime components to improve the application performance.

OC is a superset of C, so all functions in C language are still applicable when writing OC code.

OC can only declare variables on the stack, not on the stack (cgrect can be declared on the stack, because cgrect is a C structure), OC abstracts the heap memory management. No need for malloc or free to allocate or release the memory occupied by objects. The OC runtime environment abstracts this part of work into a memory management architecture called "reference count". For details, see article 29th

Article 12: Try to introduce as few header files as possible in header files of the class.

Like C and C ++, OC uses header files to separate code from "implementation Files. Almost all classes written in the OC language need to be introduced to foundation. h.

Try to use the class declaration in the header file to prevent references to the loop header file. Excessive references to the header file will increase the Compilation Time.

Article 3rd: use more literal syntax and less equivalent methods

Example:

Nsnumber * somenumber = @ 1; nsnumber * intnumber = @ 1; nsnumber * floatnumber = @ 2.5f; nsarray * animals = @ [@ "cat", @ "dog ", @ "Mouse", @ "badger"]; nsstring * dog = animals [1]; // -------------------- ID object1 = /*...... */; Id object2 = /*...... */; Id object3 = /*...... */; nsarray * arraya = [nsarray arraywithobjects: object1, object2, object3, nil]; nsarray * arrayb = @ [object1, object2, object3]; // If object2 = nil, ARRA Yb throws an exception. Only object1 and object2 are in array. // ---------------------- Nsdictionary * persondata = @ {@ "firstname": @ "Matt", @ "lastname": @ "Galloway", @ "Age": @ 28 };

Article 4th: multi-purpose type constants, less use # define preprocessing commands

You often need to define constants when writing code. For example:

#define ANIMATION_DURATION 0.3

# Define will replace the text in the compilation phase, causing a lot of unnecessary trouble. To solve this problem, we should try to take advantage of some features of the compiler. For example:

static const NSTimeInterval kAnimationDuration = 0.3;

This method defines constants that contain type information, and it is best to put this declaration in the. M file. The static const statement should not appear in the header file. Because OC does not have a namespace, it is equivalent to declaring a global variable. Static modifier indicates that the variable is defined only in this. M file (a compilation unit). If static is not added, the compiler creates an "external symbol" (external symbol) for the variable ). In this case, if another. M file also has a variable of the same name, it will cause repeated symbols (duplicate symbol ).

In fact, if a variable is declared both static and const, then the compiler will not create symbols at all, but preprocessing commands like # define, replace all the encountered variables with constants.

Sometimes a constant needs to be made public, for example:

//in the header fileextern NSString *const EOCStringConstant;//in the implement fileNSString* const EOCStringConstant = @"VALUE";

Eocstringconstant is a constant pointer. the compiler will see the extern keyword in the header file. This keyword is to tell the compiler that there will be a symbol named eocstringconstant in the global symbol table. After the link is converted into a binary file, this constant is certainly found. Because the symbols must be placed in the global symbol table, be cautious when naming constants.

Highlights of this section:

● Do not use preprocessing commands to define constants. Even if a constant value is redefined, the compiler page will not generate warning information, which will lead to inconsistent constants in the program.

● Use static const in the implementation file to define "Translation-unitspecific constant ). This type of constant is not in the global symbol table.

● Use extern in the header file to declare global constants and define their values in the implementation file.

5th: Use enumeration to indicate the status, options, and status code

Example

typedef NS_ENUM(NSUInteger,EOCConnectionState){    EOCConectionStateDisconnected,    EOCConectionStateConnecting,    EOCConectionStateConnected,};

● Use the ns_enum and ns_options macros to define enumeration types and specify the underlying data types. This ensures that enumeration is implemented by the underlying data type selected by the developer, rather than the type selected by the compiler.


Click here for other chapters

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.