为了简化程序员所需输入的代码,编译器同样提供了@property内存管理的方法
手动内存管理的关键字
1.当属性是一个普通OC对象的时候,使用retain
retain:会在setter 和 getter方法中加入一些内存管理的代码
2.当属性是一个基本数据类型的时候,使用assign
assign 直接赋值,不生成内存管理代码
3.copy 复制对象,NSString 使用copy
线程安全
4.nonatomic:非原子,不会生成线程安全的代码,速度快,iOS通常都是这种
5.atomic:原子(默认),会生成线程安全的代码,速度慢
控制权限
6.readwrite:可读可写,生成getter 与 setter方法是声明与实现
7.readonly:只读 只生成getter方法
修改方法名称
8.getter 修改生成的getter方法的名称一般情况下,BOOL类型的属性的getter方法是以is开头的
9.setter 修改生成的setter方法的名称,需要加冒号,不能在点语法中显示,一般不去修改它
#import <Foundation/Foundation.h>//------main
#import "LSPerson.h"
int main(int argc, const char * argv[]) {
//注意内存管理的黄金法则:有加必有减
LSPerson *per =[[LSPerson alloc] init];
LSIpad *ipad1 = [[LSIpad alloc] init];
per.ipad = ipad1;
[ipad1 release];
LSIpad *ipad2 = [[LSIpad alloc] init];
per.ipad = ipad2;
[ipad2 release];
[per release];
ipad1 = nil; //如果下面还有很多代码,如果不在使用这些指针,请清空他们
ipad2 = nil;
per = nil;
[per setManNew:YES]; //证明setter是可以修改setter的方法名的,记得加冒号:
BOOL isMan = per.isMan; //证明getter是可以修改getter的方法名的
NSLog(@"%d",isMan);
return 0;
}
#import <Foundation/Foundation.h>//------LSPerson.h
#import "LSIpad.h"
@interface LSPerson : NSObject
@property (nonatomic,retain)LSIpad *ipad;//OC对象用retain
@property (nonatomic,assign,readonly) int age;//基本数据类型用assign
@property (nonatomic,copy) NSString *name;//nsstring用copy
@property (nonatomic,assign,getter=isMan,setter=setManNew:) BOOL Man;//set方法需加:
@end
#import "LSPerson.h"//------LSperson.m
@implementation LSPerson
-(void)dealloc{ //为了验证而写
// [_ipad release];//如果不加release那么人回收了,ipad还在,造成内存泄露
// _ipad = nil;
self.ipad = nil; //等价与上面2句,self。ipad会进入set方法,先release,再nil
self.name = nil;
NSLog(@"%s",__func__);
[super dealloc];
}
@end
#import <Foundation/Foundation.h>//------LSIpad.h
@interface LSIpad : NSObject
@end
#import "LSIpad.h"//------LSIpad.m
@implementation LSIpad
-(void)dealloc{
NSLog(@"%s",__func__);
[super dealloc];
}
@end