引言:內存管理是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;
}
|