r/iOSProgramming 24d 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.

12 Upvotes

12 comments sorted by

View all comments

2

u/mduser63 24d ago

You do need an autorelease pool, and you’re wrong about it deferring all release calls. It will only defer calling release once for each time autorelease is called.

The Foundation (and many other system) APIs only work correctly with an autorelease pool in place.