1 对象生命周期
诞生(通过alloc或new方法实现) -> 生存(接收消息并执行操作) -> 交友(通过复合以及向方法传递参数) -> 死去(被释放掉)
引用计数(reference counting) / 保留计数(retain counting)
-
alloc
,new
,copy
: 创建对象,保留计数被设置为1 -
retain
: 保留计数加1。如[[car retain] setTire: tire atIndex:2];
表示要求car对象将其保留计数的值加1并执行setTire操作。 -
release
: 保留计数减1 -
dealloc
: 保留计数归0时自动调用 -
retainCount
: 获得对象保留计数当前值
#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;
}
对象所有权(object ownership)
如果一个对象内有指向其他对象的实例变量,则称 该对象拥有这些对象。
访问方法中的保留和释放
所有对象放入池中
-
@autoreleasepool
/NSAutoreleasePool
: 自动释放池 -
NSObject
提供autorelease
方法:
- (id) autorelease;
2 Cocoa的内存管理规则
3 异常
与异常有关的关键字
@try
@catch
@finally
@throw
捕捉不同类型的异常
@try {
} @catch (MyCustomException *custom) {
} @catch (NSException *exception) {
} @catch (id value) {
} @finally {
}
抛出异常
抛出异常的两种方式:
@throw异常名
- 向某个
NSException对象
发送raise
消息
NSException *theException = [NSException exceptionWithName: ...];
@throw theException;
[theException raise];
区别:raise
只对NSException
对象有效,@throw异常名
可用在其他对象上。