For IOS applications, the system strictly monitors the reference count of objects to ensure memory usage efficiency. When the reference count is 0, the objects are immediately released. Generally, it is enough to use release: alloc/copy/new or retain an object, use the object, and then release the object with release.
However, in this case, if a method needs to return a new object, this method is not named after alloc/copy/new, therefore, the caller will certainly not use release to balance the reference count of the returned object. On the other hand, our method cannot use release, because this will immediately release the object and return an empty object.
In this case, objective-C designed autorelease to ensure that objects can be correctly released and valid objects can be returned.
It sounds amazing. How is it implemented?
Good technology is always simple in principle. The beauty of autorelease is that it finds a suitable time to release the returned object, which is the end of the message loop. We only need to call autorelease before returning the object, and the object is added to the autorelease pool (but the reference count of the object is not reduced, so the returned object is still valid at this time), and then return, the program continues to execute until the message loop is completed, and then the temporary objects recorded in the autorelease pool are individually release.
Generally, a message runs cyclically in milliseconds or even microseconds. Therefore, autorelease is still very efficient and is indeed a clever design.