Development document for beginners: Objective-C language learning basics

Source: Internet
Author: User

Objective-CThe basics of language learning are what we will introduce in this article.ObjectThe most basic function required in programming isObjectSend a message. InObjective-C, We use the following structure to send messages:

 
 
  1. [receiver message]; 

The receiver is the one you want to send messages.Object, Message is what you want to receiveObjectMethod of execution. For example, suppose there isObjectDataTable, we want to update its data. To do this, we need to include the following statements in the program to send messages to the data table:

 
 
  1. [dataTable reloadData]; 

In Objective-C's method, the parameter is marked with a colon.

 
 
  1. [textField setEditable:YES]; 

You can have multiple parameters, each guided by a colon. Messages can also be nested, if the parameter type is the same as the return type. For example, we can read the value of the scroll bar and display it in the text area.

 
 
  1. [textField setDoubleValue:[slider doubleValue]]; 

Here, [slider doubleValue] is a parameter of [textField setDoubleValue. The Return Value of the doubleValue command is of the double type, which is consistent with the input parameter type of setDoubleValue.

For data types, in Objective-C, all object types are id. The id type variable is only the object descriptor. In fact, they are pointers to the object data structure, which is beyond the scope of our discussion. In code, we generate variables pointing to objects like other variables.

 
 
  1. id anObject; 

In Objective-C, the default returned data type is id. Therefore, if your method does not specify the return type, it will be automatically assigned as id.

You can also specify the type of a Data variable as a specific class. This is called static type. All variables pointing to objects are actually pointers to their memory locations. This method is transparent to programmers in most cases. Of course, if it is a static type, it is not transparent.

When we create an id-type variable, in fact it is implicitly a pointer to an object. Id is defined as the pointer type-the identifier of an object. But if you have a variable pointing to a string and you declare it as NSString statically, you must explicitly declare the variable as a pointer in the code. This can be achieved through the pointer declaration of c:

 
 
  1. NSString *aString; 

The asterisk before the variable name is not part of the variable name, but indicates that aString is the pointer to the NSString object. This is the only thing you need to know about the pointer property of object variables. The pointer structure of C must be used only when new variables are declared. When you reference aString, it is like other variables.

If you are not familiar with pointers or C languages, refer to C programming language compiled by Brian Kerrnighan and Dennis RitchieC. In addition, I would like to recommend using C Programming written by Steve Oulline.

Other methods for generating nested Methods

Now we have an object data type. We can generate nested methods in a different way than above. A message of the id type can be used as the receiver of other messages.

 
 
  1. double number;  
  2. number=[anArray lastObject] doubleValue]; 

Of course, we assume that the object returned by [anArray lastObject] can correspond to the doubleValue message. We have an array of objects. [AnArray lastObject] The returned object is at the top of the array, and then it receives a doubleValue message.

Define a new class in Objective-C

Now, I want to discuss with you how to define a new class in Objective-C source code. In the spirit of separation between interfaces and implementations, Objective-C defines a new class in two separate files-an interface file and an implementation file.

InterfaceThe file includes all the information required to use the class, including the declaration of all instance variables and the definition of method. Programmers study the interface file to find out which class is suitable for use. The implementation file includes the source code of how the method is implemented.

The interface and implementation of a class are usually divided into two files, although this is not mandatory for the compiler. The extension of the implementation file is. m, that is, the extension of the Objective-C source file. The extension of the interface file is. h, which is the same as that of the header file in C language. The class file name is usually the same as the class name, although this is not mandatory by the compiler. In this way, a class named "Circle" will be defined in the files Circle. h and Circle. m.

Interface file

The interface file declares the instance variables and methods that constitute the class. The structure of an interface file is:

 
 
  1. @ Interface Class Name: the name of its superclass
  2. {
  3. Instance variable Declaration
  4. }
  5. Method Declaration
  6. @ End

The interface declaration always starts with the compiler instruction @ interface and ends with @ end. The name of the class following @ interface in the first line. The class name is followed by a colon, which is followed by the name of the class inherited by your class-its superclass. If you do not specify a superclass, it will assume that you are creating a new root class, just like NSObject in Cocoa.

The first line is followed by the instance variable statement in braces. This is the data structure of the class to be operated by method. In the Circle class we assume, the instance variable declaration may be like this:

 
 
  1. double radius;  
  2. double xLacation;  
  3. double yLocation;  
  4. NSColor *color; 

The variable declaration of instance variables is always in front of the data type. We will learn later that NSColor is the class of the application library for operating colors.

After the instance variable declaration, it is the method declaration. Like Standard C functions, methods in Objective-C have return values and input parameters. In addition, the method can be either a class or an instance. The class method can only be called by class objects discussed earlier, while the instance method can be called by any object of the class. The plus sign before the method name indicates that this is a class method.

 
 
  1. + alloc 

The method statement starting with a minus sign indicates that this is an instance method.

 
 
  1. - (void) setXLocation: (double)x YLocation: (double)y; 

The return value of method is determined by the Type in brackets before the method name. Parameters are followed by colons. Multiple parameters are separated by parameter names and spaces. Like the return type of method, the Data Type of a parameter is determined by the Type in brackets before the parameter name.

If a class is associated with its superclass, the interface file of its superclass should be imported. Generally, the name of the superclass is followed by. h.

 
 
  1. #import "ItsSuperclass.h" 

# The Role Of The import Statement is similar to that of # include, which you may be familiar with. The difference is that # import is more intelligent. # The biggest advantage of import is that it automatically checks whether a file has been imported without repeated import. # Include does not perform this check.

Implementation File

The implementation file is the core part of your class code. This file includes all the code that you make your method operate-so that your class can complete some meaningful work. The interface file enables the descriptive part of your class so that the code written by other programmers can work with your class. Implement files to make your class complete the required work.

The format of the implemented file is similar to that of the interface file:

 
 
  1. # Import "class name. h"
  2. @ Implementation Class Name: superclass name
  3. {
  4. Instance variable Declaration
  5. }
  6. Method Definition
  7. @ End

The implementation of each class must reference its interface file. This part can be omitted because the superclass you inherit has been declared in the interface file. This makes it clearer that the implementation file mainly involves the concept of method implementation. In this way, in practice, only the following code is required to implement the file:

 
 
  1. # Import "class name. h"
  2. @ Implementation Class Name
  3. Method Definition
  4. @ End

The method definition is similar to the C function definition. The name should be exactly the same as the interface file without a semicolon). The method implementation code is included in a pair of braces after the name. For example, the method of our Circle class is:

 
 
  1. + Alloc
  2. {
  3. Your code
  4. }
  5. -(Void) setXLocation: (double) x YLocation: (double) y
  6. {
  7. Your code
  8. }

You may wonder why + alloc does not return a value. The default return value of Objective-C is id -- that is, it returns an object by default. + The alloc method is designed to return an object of the class, so it is not necessary to specify the return value. When talking about the + alloc method, I want to point out that you seldom need to implement this method by yourself. The NSObject class will handle this problem. + Alloc is used to allocate memory for newly created objects. The following describes how to create a new object.

Instance variables can be directly referenced in your method. You do not need to specify that all instance variables and methods are in the Same Name Domain. They are like global variables in C. In this way, we can define the second method as follows:

 
 
  1. - (void)setXLocation: (double)x YLocation: (double)y  
  2. {  
  3. xxLocation = x;  
  4. yyLocation = y;  

In addition, you can also define local variables, which have more limited functional areas. For example, in the second method above, we can add a useless intermediate variable:

 
 
  1. - (void)setXLocation: (double)x YLocation: (double)y  
  2. {  
  3. double tempX;  
  4. double tempY;  
  5. tempX = x;  
  6. tempY = y;  
  7. xLocation = tempX;  
  8. yLocation = tempY;  

You will find that any method that can be applied to Standard C functions can be applied to class methods.

Create new object

To create a newObjectTo the class of the class to which the instance you want to create belongs.ObjectSend an alloc message. For example, if you want to create an instance of the Circle class, we can do this:

 
 
  1. id aCircle;  
  2. aCircle = [Circle alloc]; 

Remember, alloc returns an object, so the variable you plan to store your created instance should be of the id type. Once a new instance is created, we need to initialize its instance variables. This allows you to send an init message to a newly created object.

 
 
  1. [aCircle init]; 

Initialization must be performed immediately after the memory is allocated, so two nested messages are generally used.

 
 
  1. aCircle=[[Circle alloc] init]; 

By default, init initializes all instance variables to 0. You can create your own initialization method, also known as constructor, to install your required initialization variables. The constructor usually starts with "init. Because the constructor needs to work withObjectSo it should be an instance method, rather than a class method like "alloc. For example, you can create a constructor for our Circle class and initialize the radius to 10. This method should be like this:

 
 
  1. - (void)initWithRadius: (double)r;  
  2. {  
  3. rradius = r;  

Any instance variables that are not initialized in your constructor are set to 0 by default.

In Project Builder

I haven't mentioned Project Builder yet. But now I want to talk about a feature related to the current discussion. Project Builder containsInterfaceAnd file template. You get a framework that inherits from the NSObject class in the basic library-all you need to do is to fill it with your own data structure and method. So now you should understand the structure of the class at the source code level, and also know how to create it easily.

Now we have basically finished the basics of getting started. Next we will go to the programming of real programs. Next time, I will introduce Interface Builder. We learn Interface Builder through experiments.

Summary: development documents for beginners:Objective-CI hope this article will help you understand the basics of language learning!

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.