开发者

Do I need to release a returned NSError object?

There are many Cocoa methods that require an NSError object as a parameter to a method, but are really a means of returning an error object to the calling method if errors exist. Is this returned object retained? That is, in the calling object code (the method to which the error is returned), does there need to be some code like:

  NSError *error;
  [a开发者_如何学CpiCall .... error:&error];

  if (error){
    [*error release];
 }

I haven't seen this anywhere, and if it does need to be released, is this the way to do it?


Returned objects are generally autoreleased. The general rule is you only call auto-/release if you earlier called copy/alloc/retain on the same object. And you wouldn't dereference error in a method call:

// right
[error code]
// wrong
[*error code]


Read the memory rules on developer.apple.com Never trust anyone restating them like 'you earlier called copy/alloc/retain' - this is not the rule, which actually says something like 'you recieved the object via a method with copy, new or alloc as part of the name'. Again, don't trust me, read developer.apple.com

As to NSError * * , thats just wrong. The METHOD takes an NSError * * as its argument, that is a pointer to an NSError * . Its the POINTER TO THE NSError * that will be populated with the address of an NSError that comes from somewhere and you have no right to assume where.

You can only pass a pointer to an NSError * - anything else is wrong.

Nor should you assume the NSError is auto-released. It may be a singleton, it could be any number of alternates. All you need to know is that 'you didn't retain it, you don't need to release it'.


You haven't allocated memory for the error, so you don't need to release it. As a rule, the framework usually adds autorelease to any objects it creates.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜