Turn: "Objective-c" Class of the first OC

Source: Internet
Author: User

Article Directory

I. Syntax Introduction
Create the first OC class with Xcode
Third, the code analysis of the first class
Fourth, add member variables
Five, adding method
Comparison with Java
Creating Objects
Accessing public member variables and methods
Note: This Objective-C project is a prelude to learning iOS development. It is also designed to allow programmers with experience in object-oriented language development to quickly get started with Objective-C. If you have no programming experience or are not interested in Objective-C and iOS development, please ignore it. Before studying this topic, it is recommended to study the C language topic first.

OC is an object-oriented language, so it also has the concepts of classes, objects, static \ dynamic methods, and member variables. So let's create the first OC class.

Back to top I. Syntax Introduction 1. Class
In Java, we can use one .java file to describe a class clearly; in OC, generally use two files to describe a class:

1> .h: Class declaration file, used to declare member variables and methods. The class declaration uses the keywords @interface and @end.

Note: The method in .h is just a declaration, it does not implement the method. In other words, it only explains the method name, the method's return value type, and the method's parameter types. It does not write the code inside the method.

2> .m: The implementation file of the class, used to implement the methods declared in .h. Class implementations use the keywords @implementation and @end.

 

2. Method
1> Method declaration and implementation must start with + or-

+ Means class method (static method)
-Representation method (dynamic method)
2> All method scopes declared in .h are public types and cannot be changed

 

3. Member variables
There are three common scopes for member variables:

1> @public is globally accessible
2> @protected is only accessible inside the class and in subclasses
3> @private is only accessible inside the class

One less scope than Java: package permission scope, for obvious reasons: OC does not have the concept of a package name.

 

Back to top Second, create the first OC class with Xcode
 1. Right-click the project folder or file and select "New File"

 

2. Select "Objective-C class" from Cocoa

 

3. Enter the class name and select the parent class

The class name is Student and the parent class is NSobject

 

4. After creating, there are two more files in the project

* Student.h is the declaration file of the class, and Student.m is the implementation file of the class

* By default, the file names of these 2 files are the same as the class name

* The compiler will only compile .m files and will not compile .h files

 

Back to top III. Code analysis of the first class
1 #import <Foundation / Foundation.h>

3 @interface Student: NSObject
4
5 @end
1> Look at line 3, the OC uses the keyword @interface to declare a class, and @interface is followed by the class name Student.

2> The colon ":" after the class name Student indicates inheritance, that is, the third line of code means that Student inherits from NSObject.

3> Because NSObject is declared in Foundation.h, the #Found file contains Foundation.h in #import on line 1.

4> @end in line 5 indicates that the declaration of the class is over. @interface and @end are used together.

 

2.Student.m-class implementation file
1 #import "Student.h"

3 @implementation Student
4
5 @end
1> Looking at line 3, the OC uses the keyword @implementation to implement a class. The class name immediately after @implementation indicates which class is to be implemented.

2> Because the Student class is declared in Student.h, the #import file contains the Student.h file on line 1. If you don't include Student.h, the third line of code will definitely report an error because it doesn't know what a student is.

3> @end in line 5 indicates that the implementation of the class is over. @implementation and @end are used together.

 

Back to top Fourth, add member variables
Under normal circumstances, we all define member variables in the header file, which is the class declaration file (.h)

1. Add a member variable to Student
1 #import <Foundation / Foundation.h>

3 @interface Student: NSObject {
4 int age; // age
5}
6
7 @end
1> Line 4 defines a member variable age of type int. The default scope of age is @protected, which can be accessed inside the Student class and subclass

2> Member variables must be written in braces {}

 

2. Set the scope of member variables
Next, add several different scope member variables to Student

 1 #import <Foundation / Foundation.h>
 2 
 3 @interface Student: NSObject {
 4 int age; // age
 5
 6 @public
 7 int no; // student number
 8 int score; // score
 9     
10 @protected
11 float height; // height
12
13 @private
14 float weight; // weight
15}
16
17 @end
There are a total of 5 member variables, of which

@public scopes are: no, score

@protected scopes are: age, height

@private scopes are: weight

 

Back to top V. How to add
Earlier we defined a member variable age, whose scope is @protected, and the outside world cannot directly access it. In order to ensure the encapsulation of object-oriented data, we can provide the get method and set method of age to let the outside world indirectly access age. Next, add the get method and set method of age to Student.

1. Declare method in Student.h
 1 #import <Foundation / Foundation.h>
 2 
 3 @interface Student: NSObject {
 4 int age; // age
 5
 6 @public
 7 int no; // student number
 8 int score; // score
 9     
10 @protected
11 float height; // height
12
13 @private
14 float weight; // weight
15}
16
17 // get method of age
18-(int) age;
19
20 // age set method
21-(void) setAge: (int) newAge;
twenty two 
23 @end
1> Line 18 declares the get method of age. The method name is called age. OC recommends that the name of the get method be consistent with the member variable (if it is in Java, it should be called getAge)

2> The topmost line 18-indicates that this is a dynamic method (+ indicates a static method). The (int) in front of age indicates that the method's return value is of type int, and the method's return value and parameter type need to be enclosed in parentheses ()

3> Line 21 declares the set method of age. The preceding-indicates a dynamic method, (void) indicates that the method has no return value.

4> In the OC method, a colon: corresponds to a parameter. Because the set method of line 21 receives an int type parameter named newAge, (int) newAge is preceded by a colon:

5> Be sure to remember: a colon: corresponds to a parameter, and the colon: is also part of the method name. So the method name of the set method on line 21 is setAge :, not setAge

 

To increase the difficulty, if you add a method to set age and height at the same time, you should write it like this:

1-(void) setAge: (int) newAge andHeight: (float) newHeight;
* This method is dynamic and has no return value. It accepts 2 parameters, so it has 2 colons:

* The method name of this method is setAge: andHeight:

* In fact, andHeight can be omitted, it is just to make the method name easier to read, and to make the colon in front of (float) newHeight: not so lonely

 

2. Implement the method in Student.m
Three methods have been previously declared in Student.h, and then they are implemented one by one

 1 #import "Student.h"
 2 
 3 @implementation Student
 4
 5 // age get method
 6-(int) age {
 7 // directly return the member variable age
 8 return age;
 9 }
10
11 // age's set method
12-(void) setAge: (int) newAge {
13 // Assign parameter newAge to member variable age
14 age = newAge;
15}
16
17 // Set age and height at the same time
18-(void) setAge: (int) newAge andHeight: (float) newHeight {
19 age = newAge;
20 height = newHeight;
twenty one }
22 @end
Line 6 implements the age method, line 12 implements the setAge: method, and line 18 implements the setAge: andHeight: method

 

Back to top VI. Comparison with Java
If it is in Java, a Student.java file can handle member variables and methods

 1 public class Student {
 2 protected int age;
 3 protected float height;
 4
 5 public int no;
 6 public int score;
 7
 8 private float weight;
 9 
10 / **
11 * age get method
12 * /
13 public int getAge () {
14 return age;
15}
16
17 / **
18 * age set method
19 * /
20 public void setAge (int newAge) {
21 age = newAge;
twenty two     }
twenty three     
twenty four     /**
25 * Set age and height at the same time
26 * /
27 public void setAgeAndHeight (int newAge, float newHeight) {
28 age = newAge;
29 height = newHeight;
30}
31}
 

Back to top VII. Creating Objects
I have already defined a Student class with member variables and methods. Let's see how to use this class to create objects.

Since the entry point of the OC program is the main function, the use of the Student class is demonstrated in the main.m file.

First complete code

 1 #import <Foundation / Foundation.h>
 2 #import "Student.h"
 3
 4 int main (int argc, const char * argv [])
 5 {
 6 @autoreleasepool {
 7 Student * stu = [[Student alloc] init];
 8         
 9 [stu releas
e];
10}
11 return 0;
12}
1. Include Student.h
Because the Student class is used, its header file is included in line 2.

#import "Student.h"
 

2. Create an object 1> In Java, use the keyword new to create an object, such as new Student (). In fact, this code does 2 things:
Allocate storage space for objects
Call Student's constructor for initialization
2> Creating objects in OC also need to do the 2 things described above in order
1) Call the static method alloc of the Student class to allocate storage space

Student * stu = [Student alloc];
OC is a method call using square brackets [], the method caller is written on the left side of the bracket, the method name is written on the right side of the bracket, with a space in the middle. So the above is a call to the static method alloc of the Student class.
The alloc method called above will return the Student object with the allocated memory. On the left side of the equal sign, a pointer variable stu pointing to the Student type is used to receive this object. Note the * on the left side of the stu. All OC objects are received using pointer variables. If you don't know about pointers, you need to remember the following: When defining a variable using a class name, you must put an * sign after the class name.
The alloc method is declared like this:
+ (id) alloc;
As you can see, its return value type is id, this id represents any pointer type, you can temporarily understand that: id can represent any OC object, similar to NSObject *.

 

2) Call the constructor of the Student object init to initialize

The Student object stu returned by the call to the alloc method cannot be used normally because the memory is only allocated and not initialized. Then the init method of the object is called to initialize

stu = [stu init];
Seeing clearly, because init is a dynamic method, it is called here using the stu variable, not the class name. init will return the initialized object and assign it to the stu variable again. At this time, the Student object stu can be used normally.

 

3) In fact, our most common approach is to use alloc and init together:

Student * stu = [[Student alloc] init];
I believe that if you have experience in object-oriented development, you can understand it at a glance. Line 7 of the complete code of main.m.

 

3. Destroy the object
Because OC does not support garbage collection, when an object is no longer used, you need to call the object's release method to release the object. We destroyed the stu object on line 9.

[stu release];
This release method can be called once here. Don't think that if you call it more than a few times, the object will be released and cleaned a little bit.

 

4. Other
1> You can also call the static method new to quickly create an object

1 Student * stu = [Student new];

3 [stu release];
However, we are still used to using alloc and init to create objects

2> Earlier we called Student's alloc, init, new methods, but you will find that Student.h does not declare these methods, why can it be called? The reason is very simple, these methods are the parent class NSObject, and the child class can of course call the methods of the parent class.

 

Back to top 8. Accessing public member variables and methods
You have successfully created a Student object earlier, and then access its public variables and methods.

 1 #import <Foundation / Foundation.h>
 2 #import "Student.h"
 3
 4 int main (int argc, const char * argv [])
 5 {
 6 @autoreleasepool {
 7 Student * stu = [[Student alloc] init];
 8         
 9 // access public variable no
10 stu-> no = 10;
11
12 // call setAge: method to set the value of the variable age
13 [stu setAge: 27];
14
15 // Call the setAge: andHeight: method to set the values of the variables age and height at the same time
16 [stu setAge: 28 andHeight: 1.88f];
17
18 // access public variable no
19 int no = stu-> no;
20 // Call the age method to get the value of the variable age
21 int age = [stu age];
twenty two         
23 // print the values of no and age
24 NSLog (@ "no is% i and age is% i", no, age);
25
26 [stu release];
27}
28 return 0;
29}
1. The Student object is created in line 7 and the object is destroyed in line 26

2. Lines 10 and 19 access the public member variable no of the Student object. If it is not a public variable, it cannot be accessed directly like this. Note the access method: Object-> Member Variable

3. Line 13 calls the setAge: method of the Student object, passing in parameter 27 to modify the value of the member variable age

4. Line 16 calls the setAge: andHeight: method of the Student object, and changes the values of the member variables age and height.

5. Line 21 calls the age method of the Student object to get the value of the member variable age.

6. Line 24 outputs the values of age and no. The output is:

2013-04-06 21: 54: 56.221 The first OC program [1276: 303] no is 10 and age is 28
Turn: [Objective-C] The first OC class


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.