"Objective-c" 05-Class of the first OC

Source: Internet
Author: User

OC is an object-oriented language, so it also has the concept of class, object, static \ Dynamic method, member variable. This is to create the first OC class.

I. Introduction to Grammar1. Class

In Java, we can describe a class with 1. java files, and in OC, you typically use 2 files to describe a class:

1>. h: A declaration file for a class that declares a member variable, method. The declaration of the class uses the keywords @interface and @end.

Note: The method in. h simply makes a declaration and does not implement the method. That is, it simply explains the method name, the return value type of the method, the type of parameter the method receives, and does not write code inside the method.

2>. M: the implementation file for the class that implements the method declared in. h. The implementation of the class uses the keywords @implementation and @end.

2. Methods

The Declaration and implementation of the 1> method must begin with a + or-

    • + denotes class method (static method)
    • -Represents an object method (dynamic method)

2> All method scopes declared in. h are of the public type and cannot be changed

3. Member Variables

There are 3 common scope of member variables:

1> @public can be accessed globally
2> @protected can only be accessed within the class and in subclasses
3> @private can only be accessed within the class

Less than Java a scope: the scope of the package permissions, for obvious reasons: OC does not have the concept of package name.

Ii. Creating a class for the first OC with Xcode

1. Right-click the project folder or file and select "New file"

2. Select "Objective-c class" of cocoa

3. Enter the class name and select the parent class

Here the class name is student, and the parent class is NSObject

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

* Student.h is a class declaration file, STUDENT.M is the implementation file for the class

* By default, these 2 files have the same file name as the class name

* The compiler compiles only. m files and does not compile. h files

third, code parsing of the first class

1.student.h-declaration file for class
1 #import <foundation/foundation.h>2 3 @interface student:nsobject4 5 @end

1> Look at line 3rd, OC uses the keyword @interface to declare a class, @interface followed by the class name student.

The colon ":" After the 2> class name student represents inheritance, meaning that the 3rd line of code means that student inherits from NSObject.

3> because NSObject is declared in Foundation.h, the Foundation.h file is included in the 1th line with #import.

4> the @end of line 5th indicates the end of the class declaration. @interface and @end are used in a matching package.

2.STUDENT.M-Class implementation file
1 #import "Student.h" 2 3 @implementation Student4 5 @end

1> See line 3rd, OC uses the keyword @implementation to implement a class. @implementation the class name immediately following it, indicating exactly which class to implement.

2> because student this class is declared in Student.h, the Student.h file is included in the 1th line with #import. If you do not include Student.h, the 3rd line of code must be an error, because it doesn't know what the hell student is.

3> the @end of line 5th indicates that the implementation of the class is complete. @implementation and @end are used in a matching package.

Iv. adding member variables

Normally, we define member variables in the header file, which is the declaration file (. h) of the class.

1. Add a member variable to a student
1 #import <foundation/foundation.h>2 3 @interface student:nsobject {4     int ages;//age 5}6 7 @end

1> The 4th row defines a member variable of type int age,age The default scope is @protected, which can be accessed within the student class and within subclasses

2> member variable must be written in curly braces {}

2. Set the scope of member variables

Next, add a few different scope member variables to student

1 #import <Foundation/Foundation.h> 2  3 @interface student:nsobject {4     int ages;//Age 5      6     @public 7     int No;//Study No. 8     int score;//score 9     @protected11     float height;//height     @private14 
    float weight; Weight}16 @end

A total of 5 member variables, where

@public scopes are: No, score

@protected scopes are: age, height

@private scopes are: weight

v. Methods of addition

Earlier we defined a member variable age, which is scoped to @protected and cannot be accessed directly by the outside world. In order to ensure the encapsulation of object-oriented data, we can provide the Get method and set method of age, so that the external access to age is indirect. Next, add the Get method and set method for age in student.

1. Declaring the method in Student.h
1 #import <Foundation/Foundation.h> 2  3 @interface student:nsobject {4     int ages;//Age 5      6     @public 7     int No;//Study No. 8     int score;//score 9     @protected11     float height;//height:     @private14     float weight;//weight}16//Age Get Method (int) age;19//Age's Set Method (void) Setage: (int) newage;22 @end

1> Line 18th declares the Get method of age, which is called Age,oc the name of the Get method is the same as the member variable (if it is in Java, it should be called getage)

2> on the 18th line-Indicates that this is a dynamic method (+ represents a static method). The (int) in front of age indicates that the return value of the method is of type int, and the return value and parameter type of the method need to be wrapped in parentheses ()

3> Line 21st declares the set method of age, preceded by-represents a dynamic method, (void) means that the method has no return value

4> in the OC method, a colon: corresponds to a parameter. Because the set method of the age in line 21st receives a parameter of type int, the parameter name is NewAge, so (int) newage preceded by a colon:

5> Be sure to remember: a colon: one parameter, and a colon: is also part of the method name. So the method name of the 21st row set method is Setage:, not Setage

If you add a method that can set age and height at the same time, you should write:

1-(void) Setage: (int) newage andheight: (float) newheight;

* This method is a dynamic method, has no return value, receives 2 parameters, so there are 2 colons:

* The method name of this method is setage:andheight:

* In fact, andheight can be omitted, it is just to let the method name read a bit fluent, also let (float) newheight before the colon: not so lonely

2. Implementing Methods in STUDENT.M

The previous 3 methods have been declared in Student.h, and the next one is to implement them

1 #import "Student.h" 2  3 @implementation Student 4  5//Age Get Method 6-(int) Age {7     //Directly returns member variable age 8     Retu RN age; 9}10//Age Set Method (void) Setage: (int) NewAge {     //assigns parameter NewAge to member variable age14 age     = newage;15}16 17//Set AG E and height18-(void) Setage: (int) newage andheight: (float) newheight {age     = newage;20     height = newheight;21} @end

The 6th line implements the age method, the 12th line Setage: The method is implemented, and the 18th line Setage:andheight: The method is implemented.

vi. comparison with Java

If it's 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 in T score; 7      8     private float weight; 9     /**11      * Age's Get method of      */13 public     int getage () {         return age;15     }16     /**18      * Age's Set method */20 public     void Setage (int. newage) {Age         = newage;22     }23     /**25      * Set both age and Height26      */27 public     void Setageandheight (int NewAge, float newheight) {Age         = newage;29         height = newheight;30     }31}

Vii. creation of objects

A student class has already been defined, and the member variables and methods are all there, so let's look at 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 the 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 release];10     }11     return 0;12}
1. Contains Student.h

Because the student class is used, it contains its header file in line 2nd.

#import "Student.h"

2. Create an Object1> in Java uses the keyword new to create objects, such as New Student (), in fact, this code does 2 things:
    • Allocating storage space to objects
    • Call the constructor method of student to initialize
2> creating objects in OC also needs to do the 2 things described above in order

1) Call the static method of the student class Alloc allocate storage space

Student *stu = [Student alloc];
    • OC is the method call is in brackets [], the method caller is written to the left of the parentheses, the method name is written on the right side of the parentheses, leaving a little space in the middle. So above is the static method alloc that called the student class.
    • The Alloc method called above returns the student object that allocates memory, uses a pointer variable stu to the student type on the left side of the equal sign to receive the object, and note the * number on the left of the Stu. All OC objects are received with pointer variables, and if you don't know the pointers, remember this: when you define a variable with a class name, you must take an * number after the class name.
    • The Alloc method is declared like this:
+ (ID) alloc;

As you can see, its return value type is ID and this ID represents any pointer type that you can temporarily understand as: ID can represent any OC object, similar to NSObject *.

2) Call the construction method of the Student object init to initialize

The student object Stu returned by the previous call to the Alloc method is not working properly because only the memory is allocated, not initialized, and then the Init method of the calling object is initialized.

Stu = [Stu init];

See, since Init is a dynamic method, it is called using the STU variable instead of the class name. Init returns the object that has already been initialized and assigns the value to the STU variable again. This time the student object Stu can be used normally.

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

Student *stu = [[Student alloc] init];

I believe there is an object-oriented development experience you can understand at a glance, in the MAIN.M complete code line 7th.

3. Destroying Objects

Because OC does not support garbage collection, it is necessary to call the release method of the object to release the object when an object is no longer being used. We destroyed the Stu object on line 9th.

[Stu release];

This release method is called here once, do not feel more calls more than a few times, the object will be released to clean a little, this will be very dangerous, prone to wild pointer errors.

4. Other

1> can also call the static method new to quickly create an object

1 Student *stu = [Student new];2 3 [Stu release];

But we're still used to creating objects using Alloc and init.

2> We called Student's alloc, Init, and new methods, but you will find that STUDENT.H does not declare these methods, why can it be called? The reason is simple, these methods are nsobject by the parent class, and the subclass can of course call the parent class's method.

Viii. accessing public member variables and methods

A student object has been successfully created, and the next step is to 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 no10         stu->no = 10;11         12
    //Call Setage: Method Set Variable Age value of         [Stu setage:27];14         //Call Setage:andheight: Method sets the value of the variable age and height 16         [Stu setage:28 andheight:1.88f];17         //Access public variable no19         int no = stu->no;20         // Call the age method to get the value of the variable age of         int age = [Stu age];22         //print No and age values of         NSLog (@ "No is%i and age is%i", no, age) ;         [Stu release];27     }28     return 0;29}

1. Line 7th creates the student object, and line 26th destroys the object

2. Lines 10th and 19th access the public member variable of the student object No, if it is not a public variable, it cannot be accessed directly like this. Note Access: Object---member variable

3. Line 13th calls the Setage: method of the Student object, passing in parameter 27 modifies the value of the member variable age

4. Line 16th invokes the Setage:andheight: Method of the Student object and modifies the value of the member variable age and height

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

6. Line 24th outputs the values of age and no, and outputs the result:

2013-04-06 21:54:56.221 First OC program [1276:303] is 28

"Objective-c" 05-Class of the first OC

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.