I did some research about static variables in objective-c and I found people declare static variables in different places which made me really confused.
For the following code, can I put
static NSUInteger counter;outside of the implementation? (Right after my #import "xxx.h")Can I put
static NSUInteger counter;inside of +initialize class method?Can I put
static NSUInteger counter;into a instance method?Most importantly, what are the differences and how to choose where to declare them?
Thanks!
@implementation MyClass
static NSUInteger counter;
+(void)initialize {
if (self == [MyClass class]) {
counter = 0;
}
}
@end
+initializemethod. Just use an initializer expression in the definition, likestatus NSUInteger counter = 1;or whatever. The only reason you might need to use a dynamic technique like+initializeis if you want to initialize to a value that's not a compile-time constant.