gnustep-dev
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: using autorelease in apple's CF


From: David Chisnall
Subject: Re: using autorelease in apple's CF
Date: Wed, 13 May 2015 09:51:47 +0100

On 13 May 2015, at 09:39, Alexey Perevalov <address@hidden> wrote:
> 
> If I truly understand, to place object into autorelease pool need to send 
> autorelease message [object autorelease], it will release ownership from 
> client code,
> in details, it just send addObject of AutoreleasePool instance, it puts 
> object into pool.
> 
> In my implementation, for example of CFString, 
> CFStringRef CFStringCreateWithCString(CFAllocatorRef allocator, const char 
> *cString, CFStringEncoding encoding){
>    return ToCFString([[NSString allocWithZone:NULL] initWithCString:cString 
> encoding:convertCFEncodingToNSEncoding(encoding)]);
> }
> 
> Just NSString is created, and initWithCString is not calling autorelase, but 
> stringWithCString is calling it.
> So if in CFStringCreateWithCString just send autorelease for newly created 
> object, no need to warry about releasing it in client code,
> in case of client is ARC enabled.

I don’t think I understand the last bit.  Autoreleasing something means ‘I have 
a temporary reference to this, which I intend to pass up the stack, and it 
should be deleted at some point in the future’.  You trade not having to 
release it in the calling code for having to retain it in the calling code if 
it does want to retain a reference to the object.

Autoreleasing is also slower than releasing because it requires adding the 
object to the pool and then popping it later.  It’s also not great for memory 
consumption, because the object will be kept alive by the reference owned by 
the autorelease pool, right until the point at which it is deleted.

This is why, in ARC mode, the compiler has the option of promoting a returned 
autoreleased object to a retained object and then explicitly releasing it.

The main reason to use autoreleased references is if you expect to have a lot 
of assignments of that reference to temporaries as the reference is propagated 
up the stack.  These won’t need retain count manipulations.

In pre-ARC Objective-C, autorelease was also a good way of returning temporary 
objects, as the caller didn’t need to free them.  With ARC, the compiler will 
do the same thing more efficiently (and reduce overall memory usage).

What problem are you actually trying to solve?

David

-- Sent from my brain




reply via email to

[Prev in Thread] Current Thread [Next in Thread]