Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ARC autorelease when using weak references?

Why can't ARC use a regular release?

Example:

[weakObject doSomething];

From what I understand, ARC turns this into:

Object *strongObject = objc_autorelease(objc_loadWeakRetained(weakObject));
[strongObject doSomething];

Why doesn't ARC do this instead?:

Object *strongObject = objc_loadWeakRetained(weakObject);
[strongObject doSomething];
objc_release(strongObject);

I'd like to do away with as many autoreleases in ARC as possible. I do a lot of async threading with GCD and I end up having to add autorelease pools a lot:

dispatch_async(self.myQueue, ^{
    @autoreleasepool{
        [weakObject doSomethingBig];
    }
});
like image 993
James Mitchell Avatar asked May 11 '13 02:05

James Mitchell


1 Answers

I cannot explain why the ARC compiler does it this way, but if I understand the generated assembly code correctly, using the following pattern

dispatch_async(self.myQueue, ^{
    Object *strongObject = weakObject;
    [strongObject doSomething];
});

is translated into objc_loadWeakRetained(), ..., objc_release(), so that the object is not put into an autorelease pool.

like image 113
Martin R Avatar answered Nov 15 '22 07:11

Martin R