1、property
我们通过声明属性(@property)来摆脱繁琐的setter和getter方法的创建。@property声明与实现文件中的另一个声明@sythesize相结合,来完成setter和getter方法的创建。@property生成设置器和访问器方法的声明,@synthesize 生成设置器和访问器方法的实现。
注意:只有当访问器不存在的时候, @synthesize才会自动生成访问器,所以,即使是使用 @synthesize声明了一个属性,你仍然可以实现自定义的getter和setter。
属性是设置实例变量的方法,也是获取实例变量的方法。
2、property 参数
有关属性参数的用法,后面内存管理会详说
举个例子,看代码才是最实在的
还是学生吧
声明部分
#import <Foundation/Foundation.h>
@interface Student : NSObject
//姓名
@property(nonatomic,strong) NSString *name;
//年龄
@property(nonatomic,assign) int age;
//婚配情况,其中自定义了getter方法的名字
@property(nonatomic,assign,getter=isMarry) BOOL marry;
//身高
@property(nonatomic,assign) float height;
//体重
@property(nonatomic,assign) float weight;
//身高除以体重得到的比例,只读属性
@property(nonatomic,assign,readonly) float biLi;
@end
实现部分
#import "Student.h"
@implementation Student
- (NSString *)description
{ //这边的self指当前类,self.name为点语法,
//self.name等同于[self name]
//同时self.name=XX等同于[self setName]=XX
return [NSString stringWithFormat:@"我叫%@,今年%d", self.name,self.age];
}
-(float)biLi{
return self.height/self.weight;
}
@end
main.m
#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Student *stu=[Student new];
stu.name=@"lisi";//相当于[stu setName=@"lisi"]
stu.age=22;
stu.marry=NO;
stu.weight=120;
stu.height=170;
// stu.biLi=2;属性中设置为只读,不能使用setter方法
NSLog(@"%@ 的 婚配情况 %d",stu.name,[stu isMarry]);
NSLog(@"%@ 的 身高体重比例 %f",stu.name,stu.biLi);
//stu.name 相当于[stu name];
}
return 0;
}
结果
2015-08-12 15:22:20.468 属性[1259:106747] lisi 的 婚配情况 0
2015-08-12 15:22:20.470 属性[1259:106747] lisi 的 身高体重比例 1.416667
复合
继承指 子类 isa 父类
复合指 一个类 hasa 一个类
还是举个小例子吧,人有宠物狗,狗类有主人
#import <Foundation/Foundation.h>
#import "Dog.h"
@interface Person : NSObject
@property(nonatomic,assign) Dog *petDog;
@end
#import <Foundation/Foundation.h>
@class Person;//至于@class的作用,为了防止人狗互相//#import,系统就会出问题
@interface Dog : NSObject
@property(nonatomic,strong) Person * owner;
@end
[更多@class和#import的区别]
(http://blog.csdn.net/guitk/article/details/7712679)