年年有"余"

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 2386|回复: 1

第二十讲:Objective-C内存管理之AutoreleasePool

[复制链接]
  • TA的每日心情
    奋斗
    2022-12-13 21:26
  • 签到天数: 371 天

    [LV.9]以坛为家II

    发表于 2014-1-12 20:48:16 | 显示全部楼层 |阅读模式
    黄金法则简述版:       如果对一个对象使用了 alloc、[mutable]copy、retain,那么必须使用相应的release或者autorelease
    前面已经有讲到过使用alloc、retain方法对retainCount进行内存管理,相对应地使用release进行内存释放,除此之外OC中引用较为智能的autorelease来进行内存管理,以下用一个程序进行说明:

    Dog.h
    1. //
    2. //  Dog.h
    3. //  AutoreleasePool
    4. //
    5. //  Created by yusian on 14-1-12.
    6. //  Copyright (c) 2014年 yusian. All rights reserved.
    7. //
    8. #import <Foundation/Foundation.h>
    9. @interface Dog : NSObject
    10. {
    11.     int _ID;
    12. }
    13. @property int ID;
    14. @end
    复制代码
    Dog.m
    1. //
    2. //  Dog.m
    3. //  AutoreleasePool
    4. //
    5. //  Created by yusian on 14-1-12.
    6. //  Copyright (c) 2014年 yusian. All rights reserved.
    7. //
    8. #import "Dog.h"
    9. @implementation Dog
    10. @synthesize ID = _ID;
    11. - (void) dealloc{
    12.     NSLog(@"dog is dealloc");
    13.     [super dealloc];
    14. }
    15. @end
    复制代码
    main.m
    1. //
    2. //  main.m
    3. //  AutoreleasePool
    4. //
    5. //  Created by yusian on 14-1-12.
    6. //  Copyright (c) 2014年 yusian. All rights reserved.
    7. //
    8. #import <Foundation/Foundation.h>
    9. #import "Dog.h"
    10. int main(int argc, const char * argv[])
    11. {
    12.     @autoreleasepool {
    13.         
    14.         Dog * dog = [[[Dog alloc] init] autorelease];
    15.         
    16.         NSLog(@"dog retainCount1 is %ld",[dog retainCount]);
    17.         
    18.         [dog retain];
    19.         
    20.         NSLog(@"dog retainCount2 is %ld",[dog retainCount]);
    21.         
    22.         [dog release];
    23.         
    24.         NSLog(@"dog retainCount3 is %ld",[dog retainCount]);
    25.         
    26.     }
    27.    
    28.     return 0;
    29. }
    复制代码
    输出结果:
    1. 2014-01-12 20:22:23.866 AutoreleasePool[3547:303] dog retainCount1 is 1
    2. 2014-01-12 20:22:23.868 AutoreleasePool[3547:303] dog retainCount2 is 2
    3. 2014-01-12 20:22:23.869 AutoreleasePool[3547:303] dog retainCount3 is 1
    4. 2014-01-12 20:22:23.869 AutoreleasePool[3547:303] dog is dealloc
    5. Program ended with exit code: 0
    复制代码


  • TA的每日心情
    奋斗
    2022-12-13 21:26
  • 签到天数: 371 天

    [LV.9]以坛为家II

     楼主| 发表于 2014-1-12 20:55:12 | 显示全部楼层
    @autoreleasepool{     }括号中的对象会被自动释放,无论对象被retain多少次,无论最终对象中retainCount值为多少,括号外面都无法再次使用该对象。上述例子中,[dog retainCount]最终为1,并没有人为释放,最终dog中的dealloc方法还是被调用,说明该对象已经被释放,即autoreleasepool实现。
    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    手机版|小黑屋|Archiver|iOS开发笔记 ( 湘ICP备14010846号 )

    GMT+8, 2024-5-2 09:27 , Processed in 0.044338 second(s), 18 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表