首页 > 代码库 > OC第十课
OC第十课
主要内容:内存管理高级(昨天的延伸)
一、属性内部的实现原理
1、assign
setter方法
- (void)setAge:(NSInteger)age
{
_age = age;
}
getter方法
- (NSInteger)age
{
return _age;
}
2、copy
@synthesize name = _name;
setter方法
@property (nonatomic , copy) NSString *name;
- (void)setName:(NSString *)name
{
if (_name != name) {
[ name release ] ;
_name = [ name copy ] ;
}
}
getter方法
- (NSString *)name
{
return [ [ _name retain ] autorelease ] ;
}
3、retain
@synthesize name = _name;
setter 方法
@property (nonatomic , retain ) NSString *name;
- (void) setName:(NSString *)name
{
if (_name != name) {
[ name release ] ;
_name = [ name retain ] ;
}
}
- (NSString *)name
{
return [ [ _name retain ] autorelease ] ;
}
二、dealloc方法
- (void)dealloc
{
[ _name release ] ;
[super dealloc] ;
}
作用:在对象引用计数为0时,系统自动调用(通常我们在dealloc中释放类的实例变量)
dealloc是NSObject的一个实例方法,与alloc对应,用于回收开辟的内存空间
注意:
1、永远不要手动调用dealloc
2、在dealloc的最后一行,必须要写 [ super dealloc ] ;
三、便利构造器的内存管理
+(instancetype)personWithName:(NSString *)name
age:(NSInteger)age;
{
return [ [ [ Person alloc ] initWithName:name age:age ] autorelease ] ;
}
四、collection的内存管理(集合会管理自己的元素)
collection就是NSArray、NSDictionary。。等容器类
collection会自动管理自己内部的元素
注意:
1、加入collection中的对象会被retain
2、移除出collection的对象会release
3、collection被释放会对内部所有元素release
示例:
Person.h文件
@interface Person : NSObject
#pragma mark - 声明属性
@property (nonatomic , sopy) NSString *name ;
@property (nonatomic , retain) NSString *gender;
@property (nonatomic , assign) NSInteger age;
#pragma mark - 声明方法
#pragma mark 初始化方法
- (instancetype)initWithName:(NSString *)name
gender:(NSString)gender
age:(NSInteger)age ;
#pragma mark 便利构造器
+ (instancetype)personWithName:(NSString)name
gender:(NSString *)gender
age:(NSInteger)age ;
@end
Person.m文件
@implementation Person
#pragma mark - 重写setter和getter方法
#pragma mark name
- (void)setName:(NSString *)name
{
if (_name != name) {
[ name release ] ;
_name = [ name copy ] ;
}
}
- (NSString *)name
{
return [ [ _name retain ] autorelease ] ;
}
#pragma mark gender
- (void)setGender
{
if (_gender != gender) {
[ gender release ] ;
_gender = [ gender retain ] ;
}
}
- (NSString *)gender
{
return [ [ _gender retain ] autorelease ] ;
}
#pragma mark - 实现方法
#pragma mark 初始化方法
- (instancetype)initWithName:(NSString *)name
gender:(NSString)gender
age:(NSInteger)age
{
if (self = [ super init ] ) {
self.name = name;
self.gender = gender;
self.age = age;
}
return self ;
}
#pragma mark 便利构造器
+ (instancetype)personWithName:(NSString)name
gender:(NSString *)gender
age:(NSInteger)age
{
return [ [ [ Person alloc ] initWithName:name gender:gender age:age ] autorelease ] ;
}
#pragma mark - 重写dealloc方法
- (void)dealloc
{
[ _name release ] ;
[ _gender release ] ;
[ super dealloc ] ;
}
@end
OC第十课