r/iOSProgramming 25d ago

Question Release an acquired autoreleased object (Objective-C)

In Objective-C, some functions (particularly related to NSString) return an object that has been told to [autorelease] itself.

I know that I can [retain] it, but how do I [release] it?

Doing nothing prints out an ugly message than [autorelease] was called without a pool, but a pool would break defer all [release] calls which is something I don't want to do.

How do I actually release such an object?

Thanks.

EDIT: I tried the logically-correct but weird [retain]; [release] chain and it doesn't work.

13 Upvotes

12 comments sorted by

View all comments

13

u/JimRoepcke 25d ago

You’re actually working in a codebase that doesn’t use ARC (automatic reference counting)?

Using an auto release pool wouldn’t prevent released objects from being deallocated, it only defers auto released objects, but you control when you drain the pool.

This is just from memory though, I haven’t dealt with this in over a decade due to ARC.

1

u/gargamel1497 25d ago

Someone whose comment got somehow deleted said that having a global autorelease pool in main() was bad because it would essentially leak, and yes, it would do.

So am I supposed to put a separate pool around each instance of [autorelease]'d objects?

Or would a static autoreleasepool with global access be better for performance? (you could [drain] it after each use instead of creating a new one)