Objective-C:如何为异步方法正确使用内存管理 [英] Objective-C: How to use memory management properly for asynchronous methods

查看:75
本文介绍了Objective-C:如何为异步方法正确使用内存管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要调用一个启动一些异步代码的方法

I need to call a method that starts some asynchronous code

MyClass* myClass = [[MyClass alloc] init];
[myClass startAsynchronousCode];

现在我不能简单地释放它,因为由于代码仍在运行,这将导致错误:

Now I can't simply release it as this would cause an error since the code is still running:

[myClass release];  // causes an error

处理内存的最佳方法是什么?

What is the best way to deal with the memory?

推荐答案

您可能需要-[MyClass startAsynchronousCode]调用回调:

You could have -[MyClass startAsynchronousCode] invoke a callback:

typedef void(*DoneCallback)(void *);

-(void) startAsynchronousCode {
  // Lots of stuff
  if (finishedCallback) {
    finishedCallback(self);
  }
}

然后像这样实例化MyClass:

and then instantiate a MyClass like this:

MyClass *myClass = [[MyClass alloc] initWith: myCallback];

myCallback可能看起来像这样:

myCallback might look like this:

void myCallback(void *userInfo) {
  MyClass *thing = (MyClass *)userInfo;
  // Do stuff
  [thing release];
}

这篇关于Objective-C:如何为异步方法正确使用内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆