ios – 在哪里发布__block变量?

ios – 在哪里发布__block变量?,第1张

概述我有以下代码片段: -(void) doSomething{ __block NSMutableArray *objArray = [[NSMutableArray alloc] initWithCapacity:0]; [self performOperationWithBlock:^(void) { //adding objects to o 我有以下代码片段:

-(voID) doSomething{    __block NSMutableArray *objArray = [[NSMutableArray alloc] initWithCapacity:0];      [self performOperationWithBlock:^(voID)      {         //adding objects to objArray         .         .         //operation with objArray finished         // 1. should objArray be released here?      }];      //2. should objArray be released here?}

我应该自动发布objArray吗?

解决方法 如果是异步调用,那么在实际块中创建NSMutableArray是有意义的:

[self performOperationWithBlock:^(voID)  {     NSMutableArray *objArray = [[NSMutableArray alloc] initWithCapacity:0];     //adding objects to objArray     .     .     //operation with objArray finished     // 1. should objArray be released here?  }];

因为在块之后你不需要它(它只对异步 *** 作的持续时间有意义),所以最后在你使用它之后释放它.或者,您可以简单地:

NSMutableArray *objArray = [NSMutableArray array];

在这种情况下,您不需要释放它.

如果是同步调用,则应在块后释放它.

注意:我假设您在使用块之前填充NSMutableArray,这意味着在块启动之前创建它是有意义的.

异步方法:

-(voID) doSomething{   // Remove the `__block` qualifIEr,you want the block to `retain` it so it   // can live after the `doSomething` method is destroyed    NSMutableArray *objArray = // created with something useful    [self performOperationWithBlock:^(voID)     {       // You do something with the objArray,like adding new stuff to it (you are modyfing it).       // Since you have the __block qualifIEr (in non-ARC it has a different meaning,than in ARC)       // Finally,you need to be a good citiZen and release it.     }];    // By the the time reaches this point,the block might haven been,or not executed (it's an async call).    // With this in mind,you cannot just release the array. So you release it insIDe the block    // when the work is done}

同步方法:

它假定您需要立即获得结果,并且在执行块之后进一步使用Array时这是有意义的,因此:

-(voID) doSomething{   // Keep `__block` keyword,you don't want the block to `retain` as you   // will release it after    __block NSMutableArray *objArray = // created with something useful    [self performOperationWithBlock:^(voID)     {         // You do something with the objArray,like adding new stuff to it (you are modyfing it).     }];    // Since it's a sync call,when you reach this point,the block has been executed and you are sure    // that at least you won't be doing anything else insIDe the block with Array,so it's safe to release it    // Do something else with the array    // Finally release it:    [objArray release];}
总结

以上是内存溢出为你收集整理的ios – 在哪里发布__block变量?全部内容,希望文章能够帮你解决ios – 在哪里发布__block变量?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1065811.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存