AutoReleasePool

2016-04-28  本文已影响368人  月下独酌灬

AutoReleasePool

自动释放池和运行循环关系

自动释放池的创建与销毁

运行循环

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        while (YES) {

            // 在控制台打印提示语
            printf("请输入你要做的操作:");

            // 保存输入的数字
            int result;

            // 接收控制太输入的数组字
            scanf("%d",&result);

            // 判断控制台输入的数字
            if (0==result) {
                NSLog(@"退出程序");
                break;
            } else if (1==result) {
                NSLog(@"点击了按钮");
            } else if (2==result) {
                NSLog(@"滚动了视图");
            }

            // insert code here...
//            NSLog(@"Hello, World!");
        }
    }
    return 0;
}

运行循环和自动释放池的关系图解

什么时候需要手动创建自动释放池?

  1. 如果在循环中创建了大量的临时变量的时候需要在循环一开始就手动创建一个自动释放池

    • If you write a loop that creates many temporary objects.You may use an autorelease pool block inside the loop to dispose of those objects before the next iteration. Using an autorelease pool block in the loop helps to reduce the maximum memory footprint of the application.
  2. 如果你生成一个子线程的时候,要在线程开始执行的时候,尽快创建一个自动释放池.否则会内存泄露.因为子线程无法访问主线程的自动释放池.

    • 自定义NSOperation和NSThread时
    • If you spawn a secondary thread.You must create your own autorelease pool block as soon as the thread begins executing; otherwise, your application will leak objects. (See Autorelease Pool Blocks and Threads for details.)
      
      

关于自动释放池的笔试题

for (int i = 0; i < largeNumber; ++i) {
    NSString *str = @"Hello World";
    str = [str stringByAppendingFormat:@" - %d", i];
    str = [str uppercaseString];
}

// 问 : 以上代码存在问题吗?

延缓释放的对象

演示延缓释放的对象

Person类中声明

@interface Person : NSObject

/// 名字
@property (nonatomic,copy) NSString *name;

/// 类方法实例化person对象
+ (instancetype)personWithName:(NSString *)name;

@end

Person类中实现

+ (instancetype)personWithName:(NSString *)name
{
    // 这是个延迟释放的对象
    Person *p = [[[Person alloc] init] autorelease];

    p.name = name;

    // 无法 return
//    [p release];

    return p;

    // 无法 release
//    [p release];
}

控制器中的使用

@interface ViewController ()

/// p1
@property (nonatomic,weak) Person *p1;
/// p2
@property (nonatomic,weak) Person *p2;

@end
- (void)viewDidLoad {
    [super viewDidLoad];

    self.p1 = [[Person alloc] init];
    self.p1.name = @"zs";
    NSLog(@"%@",self.p1.name);

    self.p2 = [Person personWithName:@"ls"];
    NSLog(@"%@",self.p2.name);

    // 手动创建自动释放池,这个不是我们讨论的
    @autoreleasepool {

    }
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"%@",self.p1.name);
    NSLog(@"%@",self.p2.name);
}
上一篇 下一篇

猜你喜欢

热点阅读