您的位置:首页 > 其它

OC简单语法复习(总结)

2014-05-17 11:36 295 查看
定义类

OC中描述类需要2个文件。

类名.h 头文件(定义变量,类名)

类名m 实现 (实现方法)

.h中的格式

@interface	类名:父类 //:为继承表示。
{
/* 此处定义变量。默认为@protected
*/

}
// 此处定义方法声明
@end


变量声明

类型 变量名;

@private 只能在类内部访问
@protected 只能在类内部和子类中访问(默认)
@public 全局都可以访问
@package(同一个框架中可以访问,不常用,可以忽略)

例如:
@private
int age_private;
int height_private;

@public
int age_public;
int height_public;


方法声明

方法格式:

-/+ (返回类型)方法名:(参数类型1)参数名1:方法名:(参数类型2)参数名2。。。; // (冒号结束)

例如:

-(void)setAge:(int)newAge; // 动态方法 返回void 方法名:setAge: 参数类型 int 参数名 newAge
- (void)setAge:(int)newAge andHeight:(float)newHeight;// 动态方法 返回void 方法名:setAge:andHeight :参数类型1 int 参数名1 newAge  参数类型2 int 参数名2 newHeight
-(int)height;// 动态方法 返回int 方法名height 无参数。


一定要记住:一个冒号:对应一个参数,而且冒号:也是方法名的一部分

构造函数声明;

例如;

-(id)initWithAge:(int)age andHeight:(int)height;


一般返回值是id 意思为能返回任何类型。id中已经包含了指针表示*,所以不用再加*来定义

其实不以init开头也可以,其他符合方法名规范的名字都行,不过。根据OC中的构造函数定义规范,一般都以init开头。

.m 方法的实现。

关键字

@implementation  类名 // 此处可以不跟父类。因为已经在.h中声明了。
//方法实现,如果在.m文件中,只有方法实现,而没有在.h中定义,则是私有方法。
/*
@implementation中实现方法。
可以使用.h中定义的_age变量是因为导入了Student.h头文件
*/
@end


方法格式:(类似.h中的定义,不过去掉;要有{}定义方法体)

-/+ (返回类型)方法名:(参数类型1)参数名1:方法名:(参数类型2)参数名2。。。{

// 方法体

}

注意事项:在set方法中千万不要使用self.变量。

例如:

-(void)setAge:(int)newAge{
// 注:千万不要使用self.age=newAge;
/*
因为OC中的点语法。self.age 会编程 [self age];
[self age:newAge];
会死循环。
*/
_age=newAge;
}


实现构造方法:(模版)

-(id)initWithAge:(int)age andHeight:(int)hegith{
/*
1。先调用super的构造方法
*/
// 防止init方法错误,如果self不为空,
if(self=[super init]){
_age=age;
_height=hegith;
/*
可以使用点语法。 不会造成死循环。
self.age=age;
self.height=height;
*/
}
return self;
}


常用:

.m中重写父类的description方法,实现自定义格式化对象的输出

self 在对象方法中,代表,对象。在类方法中代表类:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: