引言:内存管理是OC中很是重要的一起,在实际操做中有许多的细节须要咱们去注意。李杰明老师的视频由浅到深的详细讲解了内存这个版块,而且着重强调了内存管理的重要性。在这里我也详细总结了关于内存管理的一些知识。ios
管理范围:任何继承自NSObject的对象,对基本数据类型无效多线程
一:计数器的基本操做函数
1>计数器的基本结构:引用计数器4字节性能
2>引用计数器的做用atom
当使用alloc(分配存储空间)、new或者copy建立了一个新对象时,新对象的引用计数器默认值就是1。spa
当计数器为0时,整个程序退出。.net
当计数器部位0时,占用的内存不能被回收。线程
3>引用计数器的操做设计
1.retainCount指针
retainCount:获取当前计数值
回收:
(1).运行中回收 (好比植物大战僵尸中的子弹,发出去就要回收)
(2).程序退出 (mian函数没有结束,程序不会退出)
2.重写dealloc方法(相似遗言)
当一个对象被回收的时候,就会自动调用这个方法
3.retain、release
retain:返回对象自己,计数器+1;
release:没有返回值,计数器-1;
注:使用alloc,retain必须使用release
若是没有建立,就不用(auto)release。
3.谁retain,谁release
总结:善始善终,有加有减
2>set方法内存管理
例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
// Book类
@interface Book:NSObject
@end
@implementation Book
- (void)dealloc
{
NSLog(@"Book被回收了");
[super dealloc];
}
@end
// Person类
@interface Person:NSObject
{
// Book对象
Book *_book;
}
// book的set方法和get方法
- (void)setBook:(Book *)book;
- (Book *)book;
@end
@implementation Person
// book的set方法和get方法
- (void)setBook:(Book *)book
{
_book = [book retain];
}
- (Book *)book
{
return _book;
}
- (void)dealloc
{
[_book release]; // 有retain就要release
NSLog(@"Person被回收了");
[super dealloc];
}
@end
int main()
{
Book *b = [[Book alloc] init]; // b = 1
Person *b = [[Person alloc] init]; // p = 1
// p1想占用b这本书
[p1 setBook:b]; // b = 2;
[b release]; // b = 1;
b = nil;
[p1 release]; // p1 = 0, b =0
p1 = nil;
return 0;
}
|
1 2 3 4 5 6 7 8 9 |
@property (getter = isRich) BOOL rich;
// 当遇到BOOL类型,返回BOOL类型的方法名通常以is开头
// OC对象
// @property (nonatomic,retain) 类名 *属性名
@property (nonatomic,retain) Car *car;
@property (nonatomic,retain) id car; //id类型除外
// 非OC对象类型(int\float\enum\struct)
// @property (nonatomic,assign) 类名 *属性名
@property (nonatomic,assign) int age;
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
@interface Person:NSObject
+ (id)person;
+ (id)personWithAge;
@end
@implementation Person
+ (id)person
{
return [[self alloc] autorelease];
}
+ (id)personWithAge
{
Person *p = [self person];
p.age = age;
return p;
}
- (void)dealloc
{
NSLog(@"Person被回收了");
[super dealloc];
}
@end
#import <Foundation/Foundation.h>
int main()
{
@autoreleasepool
{
// 调用简单
Person *p = [Person person];
p2.age = 100;
}
return 0;
}
|