第一个oc程序,关于创建对象,声明,点语法,self关键字

来源:互联网 发布:基因工程中数据分析 编辑:程序博客网 时间:2024/06/05 20:57
今天开一个oc文章,记录自己学习iOS的经历,也希望和大家经验交流,共勉!!!

1>第一个OC的程序


一、语法简介
1.类
1>.h  类声明文件 声明变量,函数   类声明使用关键字@interface @end
2>.m  类实现文件 实现.h中的函数   类实现使用关键字@implementation @end

2.方法
1>方法的声明和实现,都必须以+或-开头
+表示静态方法(类方法)
-表示动态方法

2>.h声明的方法都是public的


3.成员变量
1> @public 全局都可以访问
2> @protected 只能在类内部和子类中访问
3> @private 只能在类内部访问


编译器只会编译.m文件,并不会编译.h文件


二、声明方法
Student.h声明get/set方法:
-(void)age; //get方法,不以get开头
-(void)setAge:(int)age; //set方法
- (void)setAge:(int)newAge andHeight:(float)newHeight;


注意:以后可以认为一个:对应一个参数


三、实现方法

Student.m实现get/set方法
//get方法实现
-(int)age{
return age;
}


//set方法实现
-(void)setAge:(int)newAge{
age=newAge;
}


// 同时设置age和height
- (void)setAge:(int)newAge andHeight:(float)newHeight {
age = newAge;
height = newHeight;
}




四、创建对象
1.调用一个静态方法alloc来分配内存
Student *stu=[Student alloc];


2.调用一个动态方法init进行初始化
stu=[stu init];


常用创建对象是以下的这种:
Student *stu = [[Student alloc]init];

五、销毁对象
[stu release];
这个release方法在这里调用一次即可


六、调用成员变量和方法
 // 调用setAge:方法设置变量age的值
[stu setAge:27];


 // 调用age方法获取变量age的值
int age = [stu age];


// 调用setAge:andHeight:方法同时设置变量age和height的值
[stu setAge:28 andHeight:1.88f];


 // 打印no和age的值
 NSLog(@"no is %i and age is %i", no, age);



七、点语法
使用点语法代替传统的get方法和set方法
 stu.age = 10; // 等价于[stu setAge:10];
int age = stu.age; // 等价于int age = [stu age];

注意:为了更好地区分点语法和成员变量访问,一般我们定义的成员变量会以下划线 _ 开头。比如叫做 _age


八、重写description方法
相当于java中的重写tostring方法


- (NSString *)description {
    return [NSString stringWithFormat:@"age=%i", _age];
 }
注意:不要在description方法中同时使用%@和self,最终会导致程序陷入死循环,循环调用description方法


九、self关键字
1> 在动态方法中,self代表着"对象"


2> 在静态方法中,self代表着"类"


3> 万变不离其宗,记住一句话就行了:self代表着当前方法的调用者


------------------------------
相信自己,永不放弃

0 0