iphone - 从后台线程访问实例变量

标签 iphone objective-c ios multithreading

假设我有一个已分配和初始化的实例变量 MyObject。然后说我这样做:

[backgroundThread performBlock:^{
    //do something with MyObject that might take some time
}];

[self dismissModalViewController]; //this releases all instance variables, right?

那么我有一个名为 backgroundThreadNSManagedObjectContext 会在后台对某个对象执行一些操作。这会立即返回并在后台执行工作,然后调用 dismissModalViewController,它会释放所有实例变量。那么,如果模态视图现在已被关闭,但 backgroundThread 仍需要使用该对象怎么办?这是一个问题吗?解决方法是什么?

还有一件事:这个 MyObject 被插入到托管对象上下文 backgroundThread 中。这是否意味着这个 NSManagedObjectContext 将保留对象,即使在关闭 View 之后也是如此?

我正在使用 ARC。

最佳答案

这里有几件事你需要考虑。首先请记住,该 block 将捕获它所指的任何内容。因此,您可能不需要做任何特别的事情,您的代码也能正常工作,具体取决于您在 block 中所做的事情。 Apple 的 Block Programming Topics 中描述了 block 捕获的规则。文档以及如何处理每个变量取决于它的类型。特别是,

In a manually reference-counted environment, local variables used within the block are retained when the block is copied. Use of instance variables within the block will cause the object itself to be retained. If you wish to override this behavior for a particular object variable, you can mark it with the __block storage type modifier.

If you are using ARC, object variables are retained and released automatically as the block is copied and later released.

另一件需要考虑的事情是对实例变量的访问可能是也可能不是线程安全的。通过声明为 atomic 的属性访问实例变量是朝着正确方向迈出的一步,但您可能需要使用互斥锁或其他技术来同步访问,具体取决于具体情况。

关于iphone - 从后台线程访问实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11277467/

相关文章:

iphone - 从 Mac App 获取 iPhone 信息的方法

iphone - 如何使导航栏看起来像这样?

ios - GIDSignInButton - 以 NSException 类型的未捕获异常终止

iOS 蓝牙 : Unknown error when writing to characteristic

ios - 检测 iOS 设备类型

ios - XMLparser 之后无法从字符串转换日期

ios - Cocos2d : Move CCsprite According to Touch

iphone - 如何避免iOS应用程序在后台过渡时暂停?

ios - 如何从核心数据 objective-c 中的两个表中获取数据

ios - 核心数据导致 endUpdates 异常