| 
TA的每日心情|  | 汗 2024-10-15 10:05
 | 
|---|
 签到天数: 372 天 [LV.9]以坛为家II | 
 
| 黄金法则简述版:       如果对一个对象使用了 alloc、[mutable]copy、retain,那么必须使用相应的release或者autorelease。 前面已经有讲到过使用alloc、retain方法对retainCount进行内存管理,相对应地使用release进行内存释放,除此之外OC中引用较为智能的autorelease来进行内存管理,以下用一个程序进行说明:
 
 Dog.h
 Dog.m复制代码////  Dog.h//  AutoreleasePool////  Created by yusian on 14-1-12.//  Copyright (c) 2014年 yusian. All rights reserved.//#import <Foundation/Foundation.h>@interface Dog : NSObject{    int _ID;}@property int ID;@end
main.m复制代码////  Dog.m//  AutoreleasePool////  Created by yusian on 14-1-12.//  Copyright (c) 2014年 yusian. All rights reserved.//#import "Dog.h"@implementation Dog@synthesize ID = _ID;- (void) dealloc{    NSLog(@"dog is dealloc");    [super dealloc];}@end
输出结果:复制代码////  main.m//  AutoreleasePool////  Created by yusian on 14-1-12.//  Copyright (c) 2014年 yusian. All rights reserved.//#import <Foundation/Foundation.h>#import "Dog.h"int main(int argc, const char * argv[]){    @autoreleasepool {                Dog * dog = [[[Dog alloc] init] autorelease];                NSLog(@"dog retainCount1 is %ld",[dog retainCount]);                [dog retain];                NSLog(@"dog retainCount2 is %ld",[dog retainCount]);                [dog release];                NSLog(@"dog retainCount3 is %ld",[dog retainCount]);            }        return 0;}
复制代码2014-01-12 20:22:23.866 AutoreleasePool[3547:303] dog retainCount1 is 12014-01-12 20:22:23.868 AutoreleasePool[3547:303] dog retainCount2 is 22014-01-12 20:22:23.869 AutoreleasePool[3547:303] dog retainCount3 is 12014-01-12 20:22:23.869 AutoreleasePool[3547:303] dog is deallocProgram ended with exit code: 0
 
 | 
 |