------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
本篇为Objec-C常用关键字的分析
开发工具:Xcode5.1.1
.h声明变量、函数(方法).m实现函数(方法)
#import//自动避免重复包含
@interface和@implementation
在O-C中,类的声明和实现是强制分开的。@interface用于类型的声明,有属性、方法、成员变量等。类型的声明以@interface开头,以@end结束,例:
//Student.h
#import <Foundation/Foundation.h>
@interface Student:NSObject
{//大括号里边写成员变量,变量命名前面通常加“_”(因为点语法)
int _age;
}
-(int) age;//-为动态方法,+为静态方法。-(void)age代表-(void)getAge,常写作-(void)age。这些方法默认都是公共的
-(void) setAge:(int) age;
@end
对应于@interface的类型声明,@implementation是类的实现,同样以@end结束,例:
//Student.m
#import <Foundation/Foundation.h>
@implementation Student
-(int) age{//注意-(void)age后面没有小括号
return _age;
}
-(int) setAge:(int) age {//该方法方法名为-(int) setAge:
_age = age ;
}
@end
对象创建
Student stu = [Student alloc];//仅定义,没有初始化
stu = [stu init]//仅初始化
//main.m
#import <Foundation/Foundation.h>
#import "Student.h"//注意不能是Student.m
int main()
{
Student *stu = [[Student alloc]init];
[stu setAge:20];
int age = [stu age];
NSLog(@"%i",age);
[stu release];
return 0;
}
Student stu=[[Student alloc] init];//定义并初始化
定义并初始化还有一种形式:[Student new];但是这种方式没有上面方式层次鲜明,因此常用上面的
[stu setAge:15 andNo:1]
点语法
等号左边相当于调用set方法,等号右边或者没有等号调用get方法
stu.age = 10 ;//相当于调用set方法
int age = stu.age ;//相当于int age = [stu age];
//main.m
#import <Foundation/Foundation.h>
#import "Student.h"//注意不能是Student.m
int main()
{
Student *stu = [[Student alloc]init];
stu.age = 20;
int age = stu.age;
NSLog(@"%i",age);
[stu release];
return 0;
}
@property和@sythesize
@property可以自动生成getter和setter的声明
@interface Person
{
int age;
}
@property int age
@end
相当于
@interface Person
{
int age;
}
-(void)setAge:(int)newAge;
-(int)age;
@end
@sythesize可以自动生成getter和setter的实现。有时要对getter和setter进行具体操作(例return age*10),则需要手动输入。
@implementation Person
@sythesize age;//如果是@sythesize _age,方法也会是set_age和_age。如果@property中未写成员变量,则会自动生成例age的私有变量。
@end
相当于
@implementation Person
-(void)setAge:(int)newAge{
age = newAge ;
}
-(int)age{
return age;
}
@end
@sythesize age = _age ;
相当于
-(void)setAge:(int)age{
_age = age ;
}
-(int)age{
return _age;
}
@sythesize如果手动写了例setAge方法,则自动不会生产setAge方法;如写了age方法,则不会自动生成age方法
当仅写@property时(Xcode4.5或以上版本)
如:
@interface Person
@property int age
@end
@implementation Person
@end
这种情况下,实现文件里相当于@sythesize age = _age
@class
@class和#import
@class Notebook;只是导入Student类,并没有导入该类的方法,也不会导入该类的成员变量(注意:后面有分号);#import "Notebook.h"是拷贝Student.h的所有,包括属性、方法等。
并且,#import不能递归引用,而@class可以,例如
//Reader.h
#import <Foundation/Foundation.h>
//#import "Notebook.h"该写法是错误的
@class Notebook;//该写法是正确的
//Reader.m
#import <Foundation/Foundation.h>
#import "Notebook.h"//在实现方法时要导入头文件
//Notebook.h
#import <Foundation/Foundation.h>
//#import "Reader.h"该写法是错误的
//Notebook.m
#import <Foundation/Foundation.h>
#import "Reader.h"//在实现方法时要导入头文件
@class比#import更节省内存。