@implementation ProductController
NSString *areaName = nil;
+ (void)setAreaName:(NSString *)areaName_ {
areaName = areaName_;
}
@end
and
@implementation ProductController
NSString *areaName = nil;
+ (void)setAreaName:(NSString *)areaName_ {
if(areaName_ != areaName) {
[areaName release];
areaName = [areaName_ copy];
}
}
- (void)dealloc {
[areaName release];
}
@end
Now which one is correct?and why?
As you seem to understand, there are no “class variables” in Obj-C. The workaround is just a C-style (global, or file-scoped) variable that you set up similarly to how you’ve shown above. First off, you should use file scope for these variables by marking them with the
statickeyword:You might also consider using a convention like
FirstLetterUppercaseto indicate the scope difference.As for memory management, you can treat it exactly like an instance variable, but one that never goes away forever:
Note that in your second example, you should NOT release the “class” variable from an instance’s
-deallocmethod. If you have more than one instance of the object, this leaves a bad dangling pointer, and defeats the purpose of the “class” variable anyways. Generally, when you use this pattern, you’ll “leak” (for some definition of leak) the class variable value, and that’s OK.