开发者

Release of method variables

Please see this code:

 -(id)MethodName:arg {
    // some stuff
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    // some more stuff
    [dateFormatter release];
}

dateFormatter is a method variable (i.e. not an instance variable; it's not defined in the header file). Yet, the method is creating a pointer and allocating memory. It turns out that the program crashes if I release the variable as in the last line, but works开发者_如何学Python ok if not. I don't understand why if I create a pointer and allocate memory, then do not need to use release. Apart from this, should I set dateFormatter to nil after its use?


What's probably happening is that you're passing the dateFormatter to some other method that just assigns it to some instance variable. Then you release it, effectively deallocating it. Finally, the class that now has a reference to deallocated memory tries to use the instance variable and the program crashes.

What you should do is have the receiving class retain the variable when it receives it (and also release the instance variable that points to it in its dealloc method).

If you're assigning it to a property, you should define it with the retain modifier, e.g.:

@property (nonatomic, retain) NSDateFormatter* dateFormatter;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜