有没有办法让后台线程释放在 ARC 下创建的对象
是的。只需将 nil 分配给后台线程上的变量。但是您应该确保该变量是唯一一个引用该值的变量。
#import <Foundation/Foundation.h>
#import <pthread.h>
pthread_t g_mainThread;
@interface Test : NSObject
@end
@implementation Test
- (void)dealloc
{
NSLog(@"Test %p was dealloced on %s", self,
g_mainThread == pthread_self() ? "the main queue" : "global queue");
}
@end
//主要
int main()
{
g_mainThread = pthread_self();
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i = 0; i < 10; ++i) {
Test *test = [[Test alloc] init];
[array addObject:test];
}
__block NSMutableArray *arrayOnGlobalQueue = array;
/*
* The array object was referenced from *array* and *arrayOnGlobalQueue* variables.
* The reference count of the array object is 2.
*/
array = nil;
/*
* The *array* variable doesn't refer the array object any more.
* The reference count of the array object is 1.
*/
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
dispatch_async(queue, ^{
/*
* Assign nil to the variable for releasing the array object
*/
arrayOnGlobalQueue = nil;
/*
* The *arrayOnGlobalQueue* variable doesn't refer the array object any more.
* The reference count of the array object is 0.
* Thus the array object was dealloced on the background thread(queue).
*/
});
dispatch_main();
return 0;
}
结果是这样的。
Test 0x7f96aac033b0 was dealloced on global queue
...
但是,一般情况下,AutoreleasePool引用对象,AutoreleasePool在主线程释放对象。
例如,如果你使用 NSMutableArray +array 类方法来实例化数组对象而不是 +alloc 和 -init 方法,
NSMutableArray *array = [NSMutableArray array];
// NSMutableArray *array = [[NSMutableArray alloc] init];
表示数组对象注册到自动释放池。因此,数组对象的引用计数为 2。使用@autoreleasepool 可以避免这种情况。
我是否需要返回非 ARC 设计
在非 ARC 下使用 release 而不是将 null 分配给 ARC 下的变量。
如果我想用 Swift 重新编写应用程序怎么办
与 Objective-C 完全一样。