OC初识
由于笔者有过C语言(入门级编程语言)和Java(同样是面向对象)的基础学习,有关代码细节不再累赘。
先看第一个代码:01.m
1 #import <Foundation/Foundation.h> // 头文件,包含系统相关函数的声明;
2
3 int main()
4 {
5 NSLog(@"Let's learn Objective C ."); // 输出函数NSLog(),函数自动换行。另外OC的字符串、关键字前必须加@。
6
7 return 0;
8 }
文件在终端编译、链接和运行:
cc 01.m -framework Foundation
Last login: Fri Aug 21 17:28:56 on console huangjian:~ student$ cd Desktop/ huangjian:Desktop student$ cc 01.m -framework Foundation huangjian:Desktop student$ ./a.out 2015-08-21 18:04:48.118 a.out[450:707] Let's learn Objective-C . huangjian:Desktop student$
第二个代码:02.m
1 #import <Foundation/Foundation.h> 2 3 @interface Car : NSObject // 类的声明 4 { 5 @public // 公有成员变量,不能给他们初始化 6 int wheels; 7 int speed; 8 } 9 - (void)run; // 方法 10 @end // 结束符,中间不能插入函数等内容 11 12 @implementation Car // 类的方法实现 13 - (void)run 14 { 15 NSLog(@"汽车跑了..."); 16 } 17 @end 18 19 20 int main() 21 { 22 Car *p = [Car new]; // 创建类的一个对象,用指针保存 23 24 p->wheels = 4; // 给对象的属性赋值,用指针访问 25 26 p->speed = 250; 27 28 NSLog(@"车子有%d个轮子,时速%dkm/h", p->wheels, p->speed); 29 30 [p run]; // 执行方法 31 32 return 0; 33 }
总结:
>>1.类的声明 @interface 类名 : 超类 { 成员变量 } - (返回值类型)方法名(参数) @end >>2.方法实现 @implementation 类名 - (void)run { 方法实现 } @end >>3.创建对象 int main() { 创建类的对象 对象属性赋值 执行方法 return 0; }
第三个代码:03.m
1 #import <Foundation/Foundation.h> 2 3 typedef enum 4 { 5 SexMan, 6 SexWoman 7 } Sex; 8 9 typedef enum 10 { 11 ColorBlack, 12 ColorRed, 13 ColorGreen 14 } Color; 15 16 typedef struct 17 { 18 int year; 19 int month; 20 int day; 21 } Date; 22 23 @interface Student : NSObject 24 { 25 @public 26 Sex sex; 27 Date birthday; 28 double weight; 29 Color favColor; 30 char* name; 31 } 32 - (void)eat; 33 - (void)run; 34 - (void)print; 35 @end 36 37 @implementation Student 38 - (void)eat 39 { 40 weight += 1; 41 NSLog(@"吃完后体重是%.2lf",weight); 42 } 43 - (void)run 44 { 45 weight -= 1; 46 NSLog(@"跑完后体重是%.2lf",weight); 47 } 48 - (void)print 49 { 50 NSLog(@"姓名:%s;",name); 51 NSLog(@"性别:%d;",sex); 52 NSLog(@"体重:%.2lf;",weight); 53 NSLog(@"颜色:%d;",favColor); 54 NSLog(@"生日:%d-%d-%d;",birthday.year,birthday.month,birthday.day); 55 } 56 @end 57 58 int main() 59 { 60 Student *stu = [Student new]; 61 62 stu->weight = 50; 63 stu->sex = SexMan; 64 stu->favColor = ColorRed; 65 66 Date d = {2015, 8, 20}; 67 s->birthday = d; 68 69 // stu->birthday.year = 2015; 70 // stu->birthday.month = 8; 71 // stu->birthday.day = 20; 72 73 stu->name = "Merry"; 74 75 [stu print]; 76 77 [stu eat]; 78 [stu eat]; 79 80 [stu run]; 81 [stu run]; 82 83 return 0; 84 }

浙公网安备 33010602011771号