@autoreleasepool-内存的分配与释放

时间 : 15-09-09 栏目 : iOS, 移动开发 作者 : noway 评论 : 0 点击 : 303 次

前言

开发过iOS、Mac的朋友应该对“ @autoreleasepool ”不陌生。只要在Xcode里创建一个工程,就能看到下面这样的代码:

//iOS program
int main(int argc, char * argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
//Command line program
int main(int argc, const char *argv[]) {
@autoreleasepool {
//...
}
return 0;
}

看,每个 main 函数的主体都被 @autoreleasepool 的Block块包在里面,也就是说,接下来所有的对象创建都在这个block里面。

那么, @autoreleasepool 的作用到底是什么呢?我们开发中可以用它来做什么呢?

可以在某些情况下,大幅度降低程序的内存占用,如下图:

  • 测试的内容:500000次循环,每次循环创建一个NSNumber实例和两个NSString实例。
  • 图:红线表示没有用 @autoreleasepool 时的内存占用。
  • 图:绿线表示用了 @autoreleasepool 优化后的内存占用!

效果是不是很明显!

代码Github地址: AutoReleasePoolTestExample Xcode 6, iOS 8, iPhone 5模拟器.

MRC 与 ARC

MRC(Mannul Reference Counting)和ARC(Automatic Reference Counting),分别对应着手动引用计数和自动引用计数。

对!是计数,不是“ GC、垃圾回收 ”什么的,就是说,在Objective-C的开发中,ARC不代表像Java那样有GC做垃圾回收,所以本质上还是要“手动”管理内存的。也就是说,我们在ARC环境下写的代码,不用自己手动插入“ retain、release这些消息 ”,ARC会在编译时为我们在合适的位置插入,释放不必要的内存。

而 @autoreleasepool 就跟对象的 release 密切相关。

@autoreleasepool 干了啥

在MRC时代,如果我们想先retain一个对象,但是并不知道在什么时候可以release它,我们可以像下面这么做:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

NSString* str = [[[NSString alloc] initWithString:@"tutuge"] autorelease];
//use str...

[pool release];
//str is released

就是说,我们可以在创建对象的时候给对象发送“ autorelease ”消息,然后当NSAutoreleasePool 结束的时候,“标记过”autorelease的对象都会被“ release ”掉,也就是会被释放掉。

但是在ARC时代,我们不用手动发送 autorelease 消息,ARC会自动帮我们加。而这个时候, @autoreleasepool 做的事情,跟 NSAutoreleasePool 就一模一样了。

什么时候用@autoreleasepool

根据 Apple的文档 ,使用场景如下:

  • 写基于命令行的的程序时,就是没有UI框架,如AppKit等Cocoa框架时。
  • 写循环,循环里面包含了大量临时创建的对象。(本文的例子)
  • 创建了新的线程。(非Cocoa程序创建线程时才需要)
  • 长时间在后台运行的任务。

利用@autoreleasepool优化循环

利用@autoreleasepool优化循环的内存占用,我觉得最有用的一点,下面就说说这个点。

如下面的循环,次数非常多,而且循环体里面的对象都是临时创建使用的,就可以用 @autoreleasepool 包起来,让每次循环结束时,可以及时的释放临时对象的内存。

//来自Apple文档,见参考
NSArray *urls = <# An array of file URLs #>;
for (NSURL *url in urls) {
@autoreleasepool {
NSError *error;
NSString *fileContents = [NSString stringWithContentsOfURL:url
 encoding:NSUTF8StringEncoding error:&error];
/* Process the string, creating and autoreleasing more objects. */
}
}

这么做的效果是极其显著地,就如本文最开始的图一样,可以自己把示例工程下回来运行下试试~

总结

@autoreleasepool看起来很不“起眼”,平常开发很容易就忽略它了,但是仔细一看,确如此有用~

 

本文标签

除非注明,文章均为( noway )原创,转载请保留链接: http://blog-old.z3a105.com/?p=530

@autoreleasepool-内存的分配与释放:等您坐沙发呢!

发表评论





       ==QQ:122320466==

 微信    QQ群


0

Aujourd’hui, une partie avec le développement du e-commerce, achats en ligne est devenu une partie de la vie pour beaucoup de gens. La mariage a commencé achats en ligne. Si vous choisissez achats les mariages en ligne, il peut être beaucoup moins cher que le salon de la Robe de mariée pas chermariée local, réduisant le budget de mariage. vous pouvez avoir beaucoup de choix si acheter de mariage en ligne. vous pouvez ramasser une robe de mariée bon marché sur Internet.
Piercing fascinerande figur, och nu tittar vi på 2016 senast brudklänning, kan du vara den vackraste bruden det!2016 senaste Bra brudklänning, söt temperament Bra design, romantiska spetsar blomma kjol, som du lägger till en elegant och charmig temperament.Kvinnan tillbaka mjuka linjer, människor brudklänningofta få en känsla av oändlig frestelse. Fall 2016 mässan, lämnar uppgifter om ditt bröllop charmig.
Yesterday afternoon, the Chinese team was training in the Guangzhou Gymnasium, when the reporter asked Zhao Yunlei the feeling of wearing the new cheap jersey , cheap jerseys online shopshe readily took a shirt from the bag crumpled ball to reporters, and she said with a smile: ” This shirt is light. ”Zhao Yunlei said: “Our material is very light like with the clothes of the tennis King Nadal, Federer, after the sweat, sweat does not drip down to the ground, when we do move, it is easy pace slipping if the sweat drip on the floor.”Tennis players Zhang Yawen, told reporters: “You might think the clothes attached to the body, fearing we swing will be affected, in fact, we do not feel anything, because the clothes are very light, very soft, put on quite comfortable. And it’s particularly good clothes to dry, washing and will dry in 15 minutes. ”
China’s sports enthusiasts NFL sweatshirt with mad love and the pursuit of, and therefore, NFL jerseys have a good market in China and development. China is a populous country, is the consumer, the economic momentum is so good, the sales prospects sportswear is immeasurable. With hot sales sweatshirt, but also to promote the importance of sports fans, on health, on the other hand is a matter of concern for the World Cup, fans wearing NFL jerseys and also can express themselves more fully love and obsession Therefore, NFL jerseys Wholesale jerseys online shopwholesale has good prospects and development in China.
ANTA-ANTA Sports Products Limited, referred to as ANTA Sports, Anta, is China’s leading sporting goods companies, mainly engaged in the design, development, manufacture and marketing of ANTA brand sporting goods, including sports footwear, apparel and accessories. Anta sweatshirt design advantages, warm stretch knit fabric, using Slim version of model, more personal fit, bid farewell to bloated, so wearing more stylish.GUIRENNIAO-This logo is a spiritual totem, smooth graphics implication unstoppable force; flexible deliver an elegant arc Wholesale jerseys china shop movement, strength and speed of the United States, a symbol of passion and rationality publicity “Heart” and “meaning”, “concept” unity; pass the fearless and enterprising mind, showing beyond the realm of self, to unstoppable force to create the future.XTEP-Xtep (China) Co., Ltd. is a comprehensive development wholesale jerseys china shop, production and marketing of Xtep brand (XTEP) sports shoes, clothing, bags, caps, balls, socks mainly large sporting goods industry enterprises.
There are a lot of fans in identifying the authenticity of the above cheap jerseys have great distress, so here to i will show you some methods to definitely affordable inexpensive cheap jerseys : Firstly, we should look at if it is working fine. China has been called the world’s factory, a lot cheap jerseys factories in China have foundries, but our cheap jerseys are all from here! Secondly, should to see whether it is the , we all know that it is difficult to get out of print once a genuine cheap cheap jerseys free shipping jersey was print. and we have all kind of stocka on the whole website, in other words, we have all you want ! Finally, look at the price, our price is not necessarily the lowest in the whole website but it must be most fair on the whole website, we certainly you will not regret later when you buy it. Of course, except that cheap jerseys, we also have the other products, such as socks, leggings and some other related products, everyone can enjoy the best services of here!

KUBET