1 對(duì)象生命周期
誕生(通過(guò)alloc或new方法實(shí)現(xiàn)) -> 生存(接收消息并執(zhí)行操作) -> 交友(通過(guò)復(fù)合以及向方法傳遞參數(shù)) -> 死去(被釋放掉)
引用計(jì)數(shù)(reference counting) / 保留計(jì)數(shù)(retain counting)
-
alloc,new,copy: 創(chuàng)建對(duì)象,保留計(jì)數(shù)被設(shè)置為1 -
retain: 保留計(jì)數(shù)加1。如[[car retain] setTire: tire atIndex:2];表示要求car對(duì)象將其保留計(jì)數(shù)的值加1并執(zhí)行setTire操作。 -
release: 保留計(jì)數(shù)減1 -
dealloc: 保留計(jì)數(shù)歸0時(shí)自動(dòng)調(diào)用 -
retainCount: 獲得對(duì)象保留計(jì)數(shù)當(dāng)前值
#import <Foundation/Foundation.h>
@interface RetainTracker : NSObject
@end
@implementation RetainTracker
- (id) init
{
if (self = [super init]) {
NSLog(@"init: Retain count of %lu .", [self retainCount]);
}
return self;
} // init
- (void)dealloc
{
NSLog(@"dealloc called. Bye Bye.");
[super dealloc];
} // dealloc
@end // RetainTracker
int main(int argc, const char * argv[]) {
RetainTracker *a = [RetainTracker new];
[a retain];
NSLog(@"%lu", [a retainCount]);
[a retain];
NSLog(@"%lu", [a retainCount]);
[a release];
NSLog(@"%lu", [a retainCount]);
[a release];
NSLog(@"%lu", [a retainCount]);
[a release];
NSLog(@"%lu", [a retainCount]); // 為什么此處是 1 不是 0嗎?
return 0;
}
對(duì)象所有權(quán)(object ownership)
如果一個(gè)對(duì)象內(nèi)有指向其他對(duì)象的實(shí)例變量,則稱 該對(duì)象擁有這些對(duì)象。
訪問(wèn)方法中的保留和釋放
所有對(duì)象放入池中
-
@autoreleasepool/NSAutoreleasePool: 自動(dòng)釋放池 -
NSObject提供autorelease方法:
- (id) autorelease;
2 Cocoa的內(nèi)存管理規(guī)則

內(nèi)存管理規(guī)則
3 異常
與異常有關(guān)的關(guān)鍵字
@try@catch@finally@throw
捕捉不同類型的異常
@try {
} @catch (MyCustomException *custom) {
} @catch (NSException *exception) {
} @catch (id value) {
} @finally {
}
拋出異常
拋出異常的兩種方式:
@throw異常名- 向某個(gè)
NSException對(duì)象發(fā)送raise消息
NSException *theException = [NSException exceptionWithName: ...];
@throw theException;
[theException raise];
區(qū)別:raise只對(duì)NSException對(duì)象有效,@throw異常名可用在其他對(duì)象上。