IOS第一天(第一个OC程序)

一、创建类

  创建类的时候,要创建两个文件,一个为头文件XXX.h,一个为源文件XXX.m

  Student.h

 1 #import <Foundation/Foundation.h>
 2 
 3 //@interface代表声明一个类
 4 //:代表继承
 5 
 6 @interface Student : NSObject {    //成员变量要定义在下面的大括号中
 7     int age;
 8 }
 9 
10 //在这里声明的所有方法都是公共的
11 
12 //age的get方法
13 //- 代表动态方法   +代表静态方法
14 - (int)getAge;
15 
16 //age的set方法
17 - (void)setAge:(int)newAge;
18 
19 @end

 

  Student.m

 1 #import "Student.h"          //导入头文件
 2 
 3 @implementation Student       //implementation代表实现这个类
 4 
 5 - (int)getAge{             //实现getAge方法的细节
 6       return age;  
 7 }
 8 
 9 - (void)setAge:(int)newAge{     //实现setAge方法的细节
10       age = newAge;  
11 }
12 
13 @end

 

 

 

二、测试

  测试要在main方法里面测试

 1 #import <Foundation/Foundation.h>
 2 
 3 #import   "Student"
 4 
 5 int main(int argc, char * argv[]){
 6       @autoreleasepool {
 7             //创建一个Student对象
 8 
 9             //1.调用一个静态方法alloc来创建对象,为stu对象分配内存空间
10       Student *stu = [Student alloc];
11 
12             //2.调用一个动态方法init初始化stu对象
13       stu = [stu init];
14 
15             //或者直接Student *stu = [[Student alloc] init];
16           [stu setAge:20];
17           int age = [stu getAge];
18           NSLog(@"age is %i",age);
19 
20             //释放对象
21           [stu release];
22 
23     }
24     
25 }     return 0;

 

posted @ 2015-10-01 12:16  ZashioM  阅读(203)  评论(0编辑  收藏  举报