Should I free the returned NSError object?

There are many Cocoa methods that require an NSError object as a method parameter, but are actually a means of returning the error object to the calling method if errors exist. Is this returned object saved? That is, in the calling object code (the method to which the error returns), is any code needed, for example:

NSError *error; [apiCall .... error:&error]; if (error){ [*error release]; } 

I haven’t seen it anywhere, and if it needs to be freed, is this a way to do it?

+7
memory-management objective-c iphone cocoa error-handling
source share
3 answers

Returned objects are usually auto-implemented. The general rule is that you only auto- / release if you previously called copy / alloc / retain on the same object. And you will not play error in the method call:

 // right [error code] // wrong [*error code] 
+7
source share

Read the memory rules on developer.apple.com. Never trust anyone who repeats them like “you used to call copy / alloc / preserve” - this is not a rule that actually says something like “you got the object through a method with copy, new or alloc as part of the name ". Again, don't trust me, read developer.apple.com

As for NSError * *, this is simply wrong. METHOD takes NSError * * as an argument, that is, a pointer to NSError *. Its POINTER TO NSError *, which will be populated with an NSError address that comes from somewhere, and you have no right to guess where.

You can pass a pointer to NSError * - something else is wrong.

Also, you should not assume that NSError is automatically thrown. It can be singleton, it can be any number of alternatives. All you need to know is that "you have not saved it, you do not need to let it go."

+6
source share

You did not allocate memory for the error, so you do not need to release it. Typically, a structure usually adds auto-advertisement to any objects that it creates.

+4
source share

All Articles