Objective-C 学习笔记,1

文件描述:

.h 类的声明文件,用户声明变量、函数(方法)

.m 类的实现文件,用户实现.h中的函数(方法)

类的声明使用关键字 @interface、@end

类的实现使用关键字@implementation、@end

Code:

------------------------------------

项目文件:

(OS X -> Command Line Tool)

  main.m

  student.h

  studen.m

 1 //
 2 //  main.m
 3 //  OC的类学习
 4 //
 5 //  Created by loong on 14-10-25.
 6 //  Copyright (c) 2014年 loong. All rights reserved.
 7 //
 8 
 9 #import <Foundation/Foundation.h>
10 
11 #import "student.h"
12 
13 int main(int argc, const char * argv[]) {
14     @autoreleasepool {
15         
16         // 创建一个对象
17         // [student alloc] 调用student类中的 alloc 静态函数
18         // [[student alloc] init] 在返回的类型中再次调用 init 函数
19         student* std = [[student alloc] init];
20         [std setAge:24];
21         int age = [std age];
22         
23         NSLog(@"age is: %i", age);
24         
25         [std setNo:17 :1];
26         
27         NSLog(@"age is: %i,no is: %i", [std age], [std no]);
28         //[std release];
29     }
30     return 0;
31 }
 1 //
 2 //  student.h
 3 //  OC的类学习
 4 //
 5 //  Created by loong on 14-10-25.
 6 //  Copyright (c) 2014年 loong. All rights reserved.
 7 //
 8 
 9 // 导入头文件
10 #import <Foundation/Foundation.h>
11 
12 // .h 文件只是用来声明那些变量和函数
13 // @interface 声明一个类
14 @interface student: NSObject { // 成员变量要声明在下面的大括号中 {}
15     int _age; // 成员变量使用_开头
16     int _no;
17 }
18 
19 // age的get方法
20 // - 代表动态方法、 + 代表静态方法 (static)
21 - (int) age;
22 - (void) setAge:(int)age;
23 
24 // 同时设置两个参数
25 - (int) no;
26 - (void) setNo:(int)age : (int) no;
27 
28 @end
 1 //
 2 //  student.m
 3 //  OC的类学习
 4 //
 5 //  Created by loong on 14-10-25.
 6 //  Copyright (c) 2014年 loong. All rights reserved.
 7 //
 8 
 9 #import "student.h"
10 
11 @implementation student
12 
13 - (int) age {
14     return age;
15 }
16 
17 - (void) setAge:(int) newAge {
18     age =newAge;
19 }
20 
21 // ===========
22 
23 - (int) no {
24     return no;
25 }
26 - (void) setNo:(int)newAge :(int)newNo {
27     age = newAge;
28     no = newNo;
29 }
30 @end

// PS: 在 oc 中关于 . 的描述(解释)

student.age 等同于 [student getAge]

student.age = 5; 等同于 [student setAge:5]