Objective-C:如何为异步方法正确使用内存管理

标签 objective-c memory-management asynchronous

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

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

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

[myClass release];  // causes an error

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

最佳答案

您可以让 -[MyClass startAsynchronousCode] 调用回调:

typedef void(*DoneCallback)(void *);

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

然后像这样实例化一个 MyClass:

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

myCallback 可能看起来像这样:

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

关于Objective-C:如何为异步方法正确使用内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2698591/

相关文章:

iOS 本地通知 : app is not asking for permissions to notify the user

objective-c - iOS 8 UISearchController 搜索栏向下移动,如果我点击搜索栏

iphone - 内存问题: simulated memory warning/didReceiveMemoryWarning

memory-management - Release Release UIWebView content from the memory,强制app释放内存

objective-c - 为什么我必须在 header 中声明协议(protocol)指定的属性,而不是类扩展(实现)

ios - 未调用 UITextField 委托(delegate)方法

java - 如果 new 失败了怎么办?

javascript - gjs 中的异步代码在调用回调之前退出

python - 在 asyncio 应用程序中将 CPU 密集型任务作为单独的进程运行会导致速度显着减慢

c# - 理解调度队列