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

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

问题描述

我需要调用启动某些异步code的方法

I need to call a method that starts some asynchronous code

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

现在我不能简单地释放它,因为这将导致一个错误,因为code仍在运行:

Now I cant 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的startAsynchronous code]调用回调:

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天全站免登陆