标签:objective 内存管理 引用计数 oc objetive-c
自动释放池以栈的形式实现:当你创建了一个新的自动释放池时,它就被添加到栈顶。接收 autorelease 消息的对象将被放入最顶的自动释放池中。如果将一个对象放入一个自动释放池中,然后创建一个新的自动释放池,再销毁该新建的自动释放池,则这个自动释放池对象扔将存在,因为容纳该对象的自动释放池仍然存在。
注意:
栈内存分配原则:从高到底分配,从低到高存取。
main.m 文件:
//
// main.m
//
// Created by on 15/4/13.
// Copyright (c) 2015年 . All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Dog.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// Person *aPerson = [[Person alloc] init] ;
// NSLog( @"引用计数:%ld", aPerson.retainCount ) ;
//
// [aPerson release] ; // 立即调用 dealloc
//
//// [aPerson autorelease] ; // 到‘}’时才 调用 dealloc
//
// NSLog( @"引用计数:%ld", aPerson.retainCount ) ;//引用计数打印不出来0
//
Person *aPerson = [[Person alloc] init] ; // 1
Dog *aDog = [[Dog alloc] init] ; // 1
aPerson.pet = aDog ; // 2
//在执行 copy 方法时,方法内部就是在执行 NSCopying 协议中的方法,copyWithZone :
Dog *newDog = [aDog copy] ;
NSLog( @"%@", newDog ) ;
[aDog release] ; // 1
[aPerson release] ; // 0
// 注意:
/*
1、引用计数的增加和减少相等,当引用计数降为0之后,不应该再使用这块内存空间;
2、凡是使用了alloc、retain或者copy、new、mutableCopy让内存的引用计数增加了,就需要使用release或者autorelease让内存的引用计数减少。在一段代码内,增加和减少的次数要相等;
3、如果拥有一个对象的所有权,那么需要在该对象不再被使用时释放其所有权。如果一个对象不归我们拥有就不要对其做释放所有权的操作。
*/
}
return 0;
}
Person.h 文件:
//
// Person.h
//
// Created by on 15/4/13.
// Copyright (c) 2015年 . All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Dog.h"
@interface Person : NSObject
@property (nonatomic, retain) NSString *name ;
@property (nonatomic, assign) NSInteger age ;
@property (nonatomic, retain) NSString *gender ;
@property (nonatomic, copy) Dog *pet ;
@end
Person.m 文件:
//
// Person.m
//
// Created by on 15/4/13.
// Copyright (c) 2015年 . All rights reserved.
//
#import "Person.h"
@implementation Person
- (void)dealloc {
NSLog( @"%s", __FUNCTION__ ) ;
// NSLog( @"%@被销毁啦", self ) ;
[_pet release] ;
[super dealloc] ;
}
@end
Dog.h 文件:
//
// Dog.h
//
// Created by on 15/4/13.
// Copyright (c) 2015年 . All rights reserved.
//
#import <Foundation/Foundation.h>
//如果一个类的对象想要被拷贝,需要遵守NSCopying协议并实现协议的相关方法
@interface Dog : NSObject<NSCopying>
@property (nonatomic, retain) NSString *name ;
@end // Dog : NSObject
Dog.m 文件:
//
// Dog.m
//
// Created by on 15/4/13.
// Copyright (c) 2015年 . All rights reserved.
//
#import "Dog.h"
@implementation Dog
- (void)dealloc {
NSLog( @"%s", __FUNCTION__ ) ;
[super dealloc] ;
}
#pragma mark - NSCopying -
- (id)copyWithZone:(NSZone *)zone {
// 根据内存信息 zone 创建副本对象
Dog *dogCopy = [[Dog allocWithZone:zone] init] ;
dogCopy.name = self.name ;
NSLog( @"副本对象的地址:%p", dogCopy ) ;
return dogCopy ;
}
@end
标签:objective 内存管理 引用计数 oc objetive-c
原文地址:http://blog.csdn.net/zhengang007/article/details/46572371