oc中类分为两个文件.h和.m
.h文件---类的声明文件,用于声明变量、函数
.m文件---类的实现文件,用于实现.h中的函数
@interface Student : NSObject{//NSObject基类 @interface用来声明一个类 :代表继承
int age;//成员变量的定义放在大括号中
}
//在写方法是,所有的类型都要用括号括起来,一个:号对应一个参数
//方法的声明 -代表动态方法 +代表静态方法
- (void)setAge:(int)age;//相当于java中的void setAge(int age){}
- (int)getAge;//相当于java中的int getAge(){}
@end
@implementation Student
-(int) getAge{
return age;
}
-(void) setAge:(int) newAge{
age = newAge;
}
@end
创建Student类的对象
//第一步调用一个静态方法alloc分配内存
Student *stu = [Student alloc];
//第二步调用一个动态方法init进行初始化
stu = [stu init];
//上面可以简化成Student *stu = [[Student alloc]init];
//调用Student中的方法
[stu setAge:10];
int age = [stu getAge];
//释放对象
[stu release];
//这里还可以通过new来创建对象,Student *stu = [Student new];
//oc中建议我们成员变量前加_,getAge改为age,所以上面的类的标准写法为
@interface Student : NSObject{
int _age;
}
-(void)setAge:(int)age;
-(int)age;
@end
@implementation Student
-(void) setAge:(int) age{
_age = age;
}
-(int) age(){
return _age;
}
@end
oc中的.语法依照上面当中的类和对象
stu.age = 100; ---这里相当于调用setAge方法[stu setAge:100]
int age = stu.age; ---这里相当于调用age方法[stu age];
//注意.xx并不是访问类中的成员变量而是调用get和set方法,根据=号来判断调用哪一个方法
//举例下面的写法正确吗(self相当于java中的this)
-(void) setAge(int age){
self._age = age;
}
-(int) age(){
return self._age;
}
//self._age = age; ---[self setAge:age]死循环无限次调用setAge方法
//同理age方法中也是不允许self._age这样写的。
oc中的构造方法与description方法
创建类Student
@interface Student : NSObject{
int _age;
int _no;
}
-(void) setAge:(int)age;
-(int) age;
-(void) setNo:(int)no;
-(int) no;
@end
@implementation Student
- (void) setAge:(int) age{
_age = age;
}
- (int) age{
return _age;
}
- (void) setNo:(int) no{
_no = no;
}
- (int) no{
return _no;
}
@end
在.h文件中声明构造方法
- (id) initAge:(int)age initNo:(int)no;//id表示任何对象
在.m中写构造方法的实现
- (id) initAge:(int)age initNo:(int)no{
/*self = [super init];
if(self != nil){//nil相当于java中的null
_age = age;
_no = no;
}
return self;*/
//上面可以简化成下面这种写法
if(self = [super init]){//谁调用方法,self指向谁
self.age = age;
self.no = no;
}
return self;
}
//调用
Student *stu [[Student alloc] initAge:15 initNo:10];
//%@代表打印一个oc对象,调用description方法,相当于java中的toString
//在.m文件中重写description方法
- (NSString *) description{
NSString *str = [NSString stringWithFormat:@"age is %i, no is %i",_age,_no];
}
变量的作用域 @public全局都可以访问 @protected只能在类内部和子类中访问
@private只能在类内部中访问 默认为protected
如果要更改变量的作用域,直接指定即可
@public
int _age;
int _no;//表示这两个都是public的
property语法(成员变量过多,set,get方法的声明与实现一大堆代码且结构一样)
@property 自动生成set和get方法的声明
@synthesize 自动生成set和get方法的实现
因此上面的Student类可以简写成这样
@interface Student : NSObject
@property int age;
@end
@implementation Student
@synthesize age;//这里默认去访问跟age同名的变量,如果找不到会自动生成一个
私有同名变量age。但oc中建议我们成员变量前加_, 这里可以改为这样@synthesize age = _age;
@end;
xcode4.5以后可以不用@synthesize,并且默认生成set和get的实现,自动生成的成员变量为_age;
上面的代码可以简写成这样
@interface Student : NSObject
@property int age;
@end
@implementation Student
@end