一 建立一个OC的类
完整的写一个函数:需要函数的声明和定义。
完整的写一个类:需要类的声明和实现。
1.类的声明
声明对象的属性和行为
1 #import <Foundation/Foundation.h> 2 3 @interface Car : NSObject 4 { 5 @public 6 int speed;//速度 7 int wheels;//轮子 8 } 9 10 - (void) initSpeed:(int)speed withWheels:(int) wheels ;11 12 - (void) run;13 14 @end
第3行:NSObject目的是让Car这个类具备创建对象的能力。
第5行:@public 可以让外部的指针间接访问对象内部的成员变量。
第 6,7行:定义对象的属性。
第10行:定义一个有入参的行为。
第12行:定义对象的行为。只要是OC对象的方法,必须以减号 - 开头。
在OC方法返回值中任何数据类型都必须用小括号()扩中。
实现@interface中声明的方法。
2.类的实现
Car 类的实现。
1 #import "Car.h" 2 3 @implementation Car 4 5 - (void)run{ 6 NSLog(@"车子跑起来。车速是%d km/h,轮子数是%d", speed, wheels ); 7 } 8 9 - (void)initSpeed:(int)speed withWheels:(int)wheels{10 self -> speed = speed;11 self -> wheels = wheels;12 }13 14 @end
第9行代码: 给对象的属性speed, wheels赋值初始值。不能在类的声明 @interface 中对属性就行初始化。
在xcode中,自动实现函数的实现:
输入 "-" , 然后输入函数的头几个字母,选中xcode自动弹出的方法。
3.类的调用
1 #import <Foundation/Foundation.h> 2 #import "Car.h" 3 4 int main(int argc, const char * argv[]) { 5 Car *car = [Car new]; 6 car -> wheels = 4; 7 car -> speed = 100; 8 [car run]; 9 10 [car initSpeed:200 withWheels:5];11 [car run];12 13 14 return 0;15 }
第5行:在OC中,想执行一些行为,就接上一个中括号[行为执行者 行为名称] 。利用类来创建对象。
[Car new]会创建出一个新对象,并且会返回新对象本身(新对象的地址)。
第6,7行:给 car所指向对象的wheels,speed属性赋值。
第8行:给car所指向的对象发送一条run消息。
二对象与函数参数
1 #import <Foundation/Foundation.h> 2 #import "Car.h" 3 4 void test1(Car *newC){ 5 newC -> wheels = 6; 6 } 7 8 void test2(Car *newC){ 9 Car *c2 = [Car new];10 c2 -> wheels = 5;11 c2 -> speed =300;12 13 newC = c2;14 newC -> wheels = 7;15 }16 17 int main(int argc, const char * argv[]) {18 Car *car = [Car new];19 car -> wheels = 4;20 car -> speed = 100;21 [car run];22 23 [car initSpeed:200 withWheels:5];24 [car run];25 26 test1(car );27 [car run];28 29 test2( car );30 [car run];31 32 return 0;33 }
第26行代码的返回结果为:车子跑起来。车速是200 km/h,轮子数是6
内存图如下:
images/loading.gif' data-original="webkit-fake-url://7250741d-6429-4e89-809e-65e7e80eed08/application.pdf" />
第29行代码的返回结果为 车子跑起来。车速是200 km/h,轮子数是6
内存图如下:
原标题:IOS基础之 (四) OC对象
关键词:IOS