Essential document for beginners: Objective-C getting started

Source: Internet
Author: User

Objective-CThis document does not teach you any knowledge about C language. If you are not familiar with the C language, you should learn the basic knowledge of the C language before reading this article. Before reading this article, you also need to understand basic object-oriented concepts.

The use of objects and the design pattern of objects are the basis for designing Cocoa programs. Understanding how they affect each other is the key to compiling your applications. For more information about these concepts, seeObjective-CObject-Oriented Programming. In addition, you can get started with the basic principles of Cocoa to learn about the design patterns used in Cocoa.

If you are familiar with the C language and have used Object-Oriented Programming before, the following content will help you learn the basic syntax of Objective-C. Many traditional object-oriented ideas, such as encapsulation, inheritance, and polymorphism, are stored inObjective-C. Although there are also some important differences, these differences will be mentioned in this Article, if you need more details available.

For details about the language and syntax of Objective-C, refer to Objective-C programming language.

 
 
  1. " src="/CuteSoft_Client/CuteEditor/Images/anchor.gif">  

Objective-C: superset of C Language

Objective-C is an ANSI superset of C language. It supports the same basic syntax as C. With C code, you can define the header file and the source code file to separate the public declaration from the detailed implementation code. The extension Table 1-1 listed under the Objective-C header file.

 
 
  1. " src="/CuteSoft_Client/CuteEditor/Images/anchor.gif">  

Table 1-1 Objective-C code. Click to enlarge the file extension)

When you want to include a header file in your code, you can use the # import command. It is similar to # include, except that it must be sure that the same file cannot be contained multiple times. Objective-C examples and documents prefer # import, so should your code.

Class

Like most other object-oriented languages, classes in Objective-C also provide basic structures to encapsulate some data with behaviors. An object is a running instance of a class, including the replication of instances declaring variables in the class in the memory, and the method pointing to the class.

The definition of classes in Objective-C requires two obvious parts: interfaces and implementations. The Interface contains the declaration of classes, the definition of member variables, and the methods associated with this class. The interface is usually in the. h file. The actual code that implements some methods that contain classes. The implementation is usually in the. m file.

Figure 1-1 shows the syntax for declaring the MyClass class, which inherits from the base class NSObject of Cocoa. The declaration of this class starts with the @ interface Compilation instruction and ends with the @ end Instruction. The parent class name is only followed by the class name (separated by a colon. Class Object variables are sometimes referred to as ivars, which are called member variables in some other languages) declared in a code block enclosed by braces {And. The object variable is followed by the method declaration list of the class. Use a semicolon as the end mark for each object variable and method.

 
 
  1. " src="/CuteSoft_Client/CuteEditor/Images/anchor.gif"> 

Figure 1-1 define a class

 
 
  1. " src="/CuteSoft_Client/CuteEditor/Images/anchor.gif">  

TIPS: this interface only declares methods, and the class can also declare attributes. For more information about attributes, see "declare attributes ".

Objective-C supports two types of variables: the strength of an object. When a variable is declared, a strong-type variable contains the class name, and a weak-type variable uses the type id to replace the object. Weak type variables are frequently used in collection classes. The actual type of objects in a collection may be unknown. If you use a strong language, you may think that using a weak type will cause problems, but in Objective-C Programs, they actually provide great flexibility and more dynamic.

The following example shows the Declaration format of strong and weak type variables:

 
 
  1. MyClass * myObject1; // strongly typed
  2. Id myObject2; // weak type

Note the number * in the first statement. In Objective-C, an object reference is a pointer. If you do not have a clear understanding of pointers, don't worry. You don't have to be a pointer expert to use Objective-C for programming. You just need to remember to add * before declaring the variable name of a strongly typed object. Weak type id itself means a pointer.

 
 
  1. " src="/CuteSoft_Client/CuteEditor/Images/anchor.gif">  

Methods and communication

Classes in Objective-C can declare two types of Methods: object methods and class methods. An object method can be executed only in an instance of this specific class. In other words, before calling an object method, you must first create an instance of this class. Class method, relative, does not need to create an instance. Of course, it can be called after the instance is created.

A Method Declaration consists of a method type identifier, a return value type, one or more signature keywords, parameter type, and name information. Figure 1-2 shows the Declaration format of the object method insertObject: atIndex.

 
 
  1. " src="/CuteSoft_Client/CuteEditor/Images/anchor.gif"> 

Figure 1-2 Syntax of method declaration


 
The Declaration starts with minus (-). Minus signs are used to identify this object method. The actual name (insertObject: atIndex :) of this method is the concatenation of all signature keywords, including colons. The colon declares the current parameter. If the method does not have a parameter, You can omit the first signature keyword. In this example, the method has two parameters.

When you want to call this method, you can communicate with the object. The communication content is the method signature and Method Request Parameter information.

The information is enclosed in brackets ([and. In the brackets, the object for receiving information is on the left, and the information includes the required parameters) is on the right. For example, to send the insertObject: atIndex: To the object named myArray, you will use the following syntax:

 
 
  1. [myArray insertObject:anObject atIndex:0]; 

To avoid declaring multiple local variables to save temporary results, Objective-C allows you to nest information. Returned values from each nested information can be used as parameters, targets, or another information. For example, you can use information to replace any variables used in the previous example. Therefore, if you have an object named myAppObject, which can access the array object and insert the object into the array, you can write the previous example as follows:

 
 
  1. [[myAppObject theArray] insertObject:[myAppObject objectToInsert] atIndex:0]; 

Objective-C also provides a period to call the accessor method. The accessor method obtains and sets the state of an object. The typical format is-(type) propertyName and-(void) setPropertyName :( type ). Using the period syntax, you can rewrite the previous example:

 
 
  1. [myAppObject.theArray insertObject:[myAppObject objectToInsert] atIndex:0]; 

You can also use the period syntax to assign values:

 
 
  1. myAppObject.theArray = aNewArray; 

Writing with different syntaxes is also relatively simple,

 
 
  1. [myAppObject setTheArray:aNewArray];. 

Although the previous example is to send information to an instance of a class, you can also send information to the class itself. When you want to communicate to a class, the method you specify must be defined as a class method rather than an entity method.

Typically, you can use the class method to create a new instance of the class or access some shared information about the class. The Declaration syntax of the class method is different from that of the object method. Use the plus sign (+) instead of the minus sign (-) as the identifier of the method type.

The following example shows how to use a class method as a factory method of a class. In this example, the method array is a class method of NSArray-inherited from NSMutableArray-it is used to allocate and initialize a new instance of the class and return it to the code.

 
 
  1. NSMutableArray * myArray = nil; // nil is equivalent to NULL
  2. // Create some new arrays and assign them to the variable myArray.
  3. MyArray = [NSMutableArray array];

Listing 1-1 shows the implementation code of the MyClass class in the previous example. Like the declaration of a class, the class implementation is identified by two compilation commands-here, @ implementation and @ end. These commands provide the range information required by the compiler to locate the closed method of the corresponding class. The method declaration must match the declaration in the interface, excluding the content in the code block.

 
 
  1. " src="/CuteSoft_Client/CuteEditor/Images/anchor.gif">  

Listing 1-1 Implementation of A Class

 
 
  1. @implementation MyClass  
  2.    
  3. - (id)initWithString:(NSString *)aName  
  4. {  
  5.  self = [super init];  
  6.  if (self) {  
  7.  name = [aName copy];  
  8.  }  
  9.  return self;  
  10. }  
  11.  
  12. + (MyClass *)createMyClassWithString: (NSString *)aName  
  13. {  
  14.  return [[[self alloc] initWithString:aName] autorelease];  
  15. }  
  16. @end  
  17. " src="/CuteSoft_Client/CuteEditor/Images/anchor.gif"> 

Declare attributes

Declared attributes are convenient methods to replace declarations and simply implement accessors.

The class interface can contain attribute declarations and method declarations. The basic definition uses @ property to compile the command, followed by the type information and attribute name. You can also customize configuration attributes, such as how the accessor method is executed. The following example shows a simple attribute declaration:

 
 
  1. @ Property BOOL flag;
  2. @ Property (copy) NSString * nameObject; // copy the object when the value is assigned.
  3. @ Property (readonly) UIView * rootView; // declare a read-only Method

Each readable attribute specifies a method with the same name as this attribute. Specify an additional method for each writable attribute in the format of setPropertyName. The first letter of the attribute name must be capitalized.

In the implementation of your class, you can use @ synthesize to compile the instruction to require the compiler to create a method according to the declared specification:

 
 
  1. @synthesize flag;  
  2. @synthesize nameObject;  
  3. @synthesize rootView; 

You can merge the @ synthesize statement into a row. If you want:

 
 
  1. @synthesize flag, nameObject, rootView; 

In fact, attributes reduce the number of lengthy code that you have to write. Because most accessors are executed in a similar way, each attribute exposed in the class is removed to implement repeated read/write methods. On the contrary, you only need to specify the behavior you want to use the attribute, and the actual read/write method will be generated during compilation.

To learn how to declare attributes in your class, see "declare attributes" in Objective-C programming language.

String

As a superset of C language, Objective-C and C language support the same conventions on the specified string. In other words, characters are enclosed in single quotes, and strings are enclosed in double quotes. However, the Objective-C framework typically does not use a C-language string. They pass strings as NSString objects.

The NSString class provides an object encapsulation string, which has all the advantages you want, including creating memory management for strings of any length, and supporting Unicode and printf-format formatting tool sets, there are more. Because such strings are widely used, Objective-C provides a shortcut to create an NSString object based on constants. to use this shortcut, you must add the @ symbol before the regular double quotation mark string. The following example shows how to use it:

 
 
  1. NSString * myString = @ "My String \ n ";
  2. NSString * anotherString = [NSString stringWithFormat: @ "% d % @", 1, @ "String"];
  3. // Create an Objective-C toe based on a C string
  4. NSString * fromCString = [NSString stringWithCString: "a c string" encoding: NSASCIIStringEncoding];

Protocol

Methods declared by a protocol can be implemented by any class. The Protocol itself has no class. They simply define an interface to implement other objects reliably. When you implement a protocol method in your class, you can say that your class complies with that protocol.

The Protocol is frequently used to specify an interface for the drag object. The best way to look at the interaction between protocols, delegates, and other objects is to look at an example.

The UIApplication class implements the behavior required by an application. You do not need to force the subclass UIApplication to receive simple notifications with the current program status. Instead, the UIApplication class sends those notifications by calling the specific methods of the delegate object it assigns. Objects implementing the UIApplicationDelegate protocol method can receive those notifications and provide appropriate responses. Wrap the protocol name with "<>" and put it behind the inherited class to specify the protocol that your class complies with or uses. You do not need to declare your methods to implement the Protocol.

 
 
  1. @interface MyClass : NSObject <UIApplicationDelegate, AnotherProtocol> {  
  2. }  
  3. @end 

The Declaration of the Protocol looks similar to the interface of a class. The difference is that the Protocol does not have a parent class and cannot define entity variables. The following example shows a simple protocol with a method:

 
 
  1. @protocol MyProtocol  
  2. - (void)myProtocolMethod;  
  3. @end 

In many examples of delegated protocols, a protocol is similar to the method defined in the Protocol. Some protocols require you to specify the protocols you support. You can specify required and optional methods. When you want to push your development to a deeper level, you should spend a little more time learning protocols and how to use them-"protocols" in Objective-C programming languages.

 
 
  1. " src="/CuteSoft_Client/CuteEditor/Images/anchor.gif">  

More information

The above content mainly aims to familiarize you with the basics of Objective-C language. The topic described here covers the language functions most likely to be encountered when you read the document. This content is not the only function of this language. We encourage you to read more about this language.

Summary: required documents for beginners:Objective-CI hope this article will be helpful to you!

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.