Objective-C notes Class 2, object and method, objective-c notes

Source: Internet
Author: User

Objective-C notes Class 2, object and method, objective-c notes

An object is an object. Object-Oriented programming can be seen as an object and what you want to do with it. This is different from the C language, which is usually called a procedural language. In C language, we usually consider what to do first and then focus on objects. This is almost always the opposite of the thinking process of objects.

In the object-oriented language, your car is an example of a car. Car is the name of the class, and this instance is created from the class. Therefore, every time you create a new car, a new instance of the car will be created, and each instance of the car is called an object.

Object Operations performed by objects
Your car Driving
Car Wash


Each instance or object contains not only information about the original features obtained from the manufacturer, but also its current features that can be dynamically changed. When you are driving a car, the mailbox oil is getting exhausted, the car is getting dirty, and the tires are getting worn out.

Object usage can affect the object status. If the method is to "refuel the car", the email address of the car will be filled after this method is executed. This method affects the status of the car mailbox.

The key concept here is that an object is a unique expression of a class. Each object contains information that is usually private to the object. Methods to access and change the data.


[ClassOrInstance method];

In this statement, the left square brackets are followed by the class name or the Instance name of the class. It can be followed by one or more spaces, and the space is followed by the method to be executed. Finally, end with parentheses and semicolons. When a class or instance is requested to execute an operation, a message is sent to it. The receiver of the message is called the receiver. Therefore, there is another way to represent the general format described above:

[Receiver message];

Review the previous list and use this new syntax to write all the methods for it. Before that, you need to get a new car and go to the manufacturing factory to buy one:

YourCar = [Car new]; get a new car // This is really detailed, isn't it a new object! YourCar is your car now. You can use it to reference an instance of the car.

A new car requires a new car method, so this new method can be called a factory method, or a class method:

[YourCar prep]; get it ready for first-time use

[YourCar drive]; drive your car

[YourCar wash]; wash your car

[YourCar getGas]; put gas in your car if you need it

[YourCar service]; service your car


[YourCar topDown]; if it's a convertible

[YourCar topUp];

CurrentMileage = [yourCar odometer];

The last example shows the information returned by the instance method, that is, the current mileage, which can be seen through the ODPS table (odometer. We store this information in the currentMileage variable in the program.

Here is an example of using a specific value as a method parameter, which is different from calling a method directly:

[YourCar setSpeed: 55]; set the speed to 55 mph

Your sister Sue can use the same method for her own car instance;

[SuesCar drive];

[SuesCar wash];

[SuesCar getGas];

Applying the same method to different objects is one of the main concepts behind object-oriented programming.


Objective-C class used to process scores

If you want to write a program to process scores, you may need to process addition, subtraction, multiplication, division, and other operations. A Fraction class is created:

1 // 2 // Fraction. h 3 // 4 // Created by on 15/11/13. 5 // Copyright©2015. all rights reserved. 6 // interface section 7 8 # import <Foundation/Foundation. h> 9 10 @ interface Fraction: NSObject11 12-(void) print; 13-(void) setNumerator :( int) n; 14-(void) setDenominator :( int) d; 15-(int) numberator; 16-(int) denominator; 17 18 @ end
1 // 2 // Fraction. m 3 // HelloWorld 4 // 5 // Created by on 15/11/13. 6 // Copyright©2015. all rights reserved. 7 // 8 9 # import "Fraction. h "10 11 @ implementation Fraction12 {13 int numberator; 14 int denominator; 15} 16-(void) print {17 NSLog (@" % I/% I ", numberator, denominator); 18} 19-(void) setNumerator :( int) n {20 numberator = n; 21} 22-(void) setDenominator :( int) d {23 denominator = d; 24} 25-(int) numberator26 {27 return numberator; 28} 29-(int) denominator30 {31 return denominator; 32} 33 @ end34 // ---- program part ---- 35 # import <Foundation/Foundation. h> 36 int main (int argc, const char * argv []) 37 {38 @ autoreleasepool {39 Fraction * myFraction; 40 41 // create a score instance alloc allocation space init initialization 42 myFraction = [[Fraction alloc] init]; 43 // myFraction = [myFraction init]; 44 45 46 // Fraction * fact = [[Fraction alloc] init]; 47 48 // set score to 1/349 [myFraction setNumerator: 1]; 50 [myFraction setDenominator: 3]; 51 52 // [fact setDenominator: 3]; 53 // [fact setNumerator: 7]; 54 55 // use The print method to display The score 56 NSLog (@ "The value of myFraction is: % I/% I", [myFraction numberator], [myFraction denominator]); 57 // [myFraction print]; 58 // 59 // NSLog (@ "Second fraction is:"); 60 // [fact print]; 61} 62 return 0; 63}

@ Interface is used to describe the Class and Class methods; @ implementation is used to describe the data (the data stored in the strength variable of the Class Object), and implement the instance code to declare the method in the interface; the program code in the program section achieves the intended purpose of the program.


@ Interface

The general format is similar:

@ Interface NewClassName: ParentClassName


@ End

According to the Conventions, the class name generally starts with an uppercase letter.

  • Variable name naming rules: the name must start with a letter or underscore (_), followed by any (upper or lower case) letter, underline or 0 ~ 9.
  • Some names cannot be used as variable names, such as int. Because its purpose has a special meaning for the Objective-C compiler, this usage is called reserved name or reserved word. (That is, the system keyword)
  • In Objective-C, uppercase and lowercase letters are different. Variable names sum, Sum, and SUM indicate different variables.

Class Method and instance method

-(Void) print;

The negative sign (-) at the beginning notifies the Objective-C compiler that this method is an instance method. In addition, there is another option, namely (+), which represents the class method. A class method is a method that performs certain operations on the class itself, for example, creating a new instance of the class.

1. Return Value

-(Int) currentAge;

When declaring a new method, you must tell the OC compiler whether the method has a return value. The Return Value Type of the method is in brackets! This method specifies the instance method named currentAge to return an integer value.

For example, double-precision value. void indicates no return type.

2. method parameters

-(Void) setNumberator: (int) n;

This is an instance method with no return value type. int is used to specify the parameter type. For setNumberator, the parameter name is n. This name can be arbitrary.


@ Implementation

The @ implementation part contains the instance code of the method declared in the @ interface part, and the Data Type stored in the class object needs to be specified. (Interface class and implementation class)

@ Implementation:

@ Implementation NewClassName





@ End

The memberDeclarations section specifies the type of data to be stored in Fraction and the name of the data type.



The program section contains the code to solve specific problems. If necessary, it can span multiple files. There must be a function named main somewhere, which is usually the place where the program starts to run.


Fraction * myFraction;

This line indicates that myFraction is an object of the Fraction type.

MyFraction = [[Fraction alloc] init];

Alloc is short for allocate because it allocates memory storage space for new scores.

The init method is used to initialize instance variables of the class. Note that you are sending the init message to myFraction. That is to say, a special Fraction object needs to be initialized here. Therefore, it is not sent to the class, but to an instance of the class.

The init method can also return a value, that is, the object to be initialized. Store the returned values in the variable myFraction of the Fraction.

Let's return to Fraction * myFraction again;

  The asterisk (*) before myFraction indicates that myFraction is a reference (or pointer) of the Fraction object ). The variable myFraction does not actually store Fraction data, but stores a reference (actually a memory address), indicating the location of the object data in the memory.



Okay! Others are setter and getter, which are not described in detail and should be well understood.


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.