Hello!
The documentation on NSAutoreleasePool contains the following assertion:
If you are making Cocoa calls outside of the Application Kit’s main thread—for example if you create a Foundation-only application or if you detach a thread—you need to create your own autorelease pool.
It looks like yet it is not required anymore. For instance, the look at the code below:
#import <Cocoa/Cocoa.h>
#include <pthread.h>
@interface MyObject : NSObject
@property (copy, nonatomic) NSString* str;
@end
@implementation MyObject
- init {
self = [super init];
NSLog(@"init %@", self);
return self;
}
- (void) dealloc {
NSLog(@"dealloc %@", self);
self.str = nil;
[super dealloc];
}
@end
void* thread_main (void* ptr)
{
MyObject* obj = (__bridge id)ptr;
CFAutorelease(ptr);
NSLog(@"%p: %@", pthread_self(), obj.str);
return 0;
}
int main(int argc, const char* argv[argc])
{
MyObject* obj = [MyObject new];
obj.str = [@"test string" copy];
NSLog(@"1: %@", obj.str);
pthread_t pth;
if (pthread_create (&pth, NULL, thread_main, (__bridge void*)obj)
|| pthread_join(pth, NULL))
{
perror("pthread: ");
}
NSLog(@"2: %@", obj.str);
return 0;
}
iIf compile it with as following (with MRC):
clang -gfull -fno-objc-arc -o test_autorelease test_autorelease.m -framework Cocoa
it prints
2019-02-20 17:11:40.814 test_autorelease[52994:2010949] init <MyObject: 0x7f8ed760b820>
2019-02-20 17:11:40.814 test_autorelease[52994:2010949] 1: test string
2019-02-20 17:11:40.815 test_autorelease[52994:2010951] 0x700005f17000: test string
2019-02-20 17:11:40.815 test_autorelease[52994:2010951] dealloc <MyObject: 0x7f8ed760b820>
2019-02-20 17:11:40.815 test_autorelease[52994:2010949] 2: (null)
So, it is clear that after printing the test string in background thread, the object was released and dealloced. If to comment line 27 with call to CFAutorelease(), the ouput is following:
2019-02-20 17:16:03.505 test_autorelease[53053:2015162] init <MyObject: 0x7fccbfc006d0>
2019-02-20 17:16:03.505 test_autorelease[53053:2015162] 1: test string
2019-02-20 17:16:03.505 test_autorelease[53053:2015164] 0x700003be3000: test string
2019-02-20 17:16:03.505 test_autorelease[53053:2015162] 2: test string
So the object is not deallocated.
It looks like either documentation is not updated, or there is something I've missed.
Could anybody please comment on this?