How do I create a local autorelease pool to save up memory?

删除回忆录丶 提交于 2020-01-01 09:59:50

问题


Apple says that this is a good idea for saving memory. What would that look like in code?


回答1:


Usualy you don't need to create autorelease pool, because system cares about this. But, sometimes you need to do this. It's usualy in big loops. Code would look like this:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int i;    
for (i = 0; i < 1000000; i++) {    
  id object = [someArray objectAtIndex:i];
  // do something with object
  if (i % 1000 == 0) {
    [pool release];
    pool = [[NSAutoreleasePool alloc] init];
  }
}
[pool release];

Autorelease pools are kept as a stack: if you make a new autorelease pool, it gets added to the top of the stack, and every autorelease message puts the receiver into the topmost pool.



来源:https://stackoverflow.com/questions/742196/how-do-i-create-a-local-autorelease-pool-to-save-up-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!