Why does the static integer in the class increment?
I am wondering why in the following code the static integer does not stay 0? Is it because in objective-c c开发者_如何转开发lasses are objects, too and the CoolClass Class is kind of kept around like a singleton?
@interface CoolClasss : NSObject
+(void)staticMethod;
@end
@implementation CoolClass
static int integer=0;
+(void)staticMethod {
NSLog(@"integer: %d", integer);
integer++;
}
@end
int main (int argc, const char * argv[]) {
for (int i=0; i<10; i++) {
[CoolClass staticMethod];
}
return 0;
}
As with most OO languages, static variables do not belong to an individual object. That means a single copy of the variable is shared by all objects in that class. It also means the variable exists regardless of whether there are any objects in existence for that class.
What's happening here is that you're calling the static method which increments the static variable. No surprises there.
CoolClass
is not a singleton. A singleton is defined as a class that never allows itself to have more then one object.
Here (and in C++ for that matter), you can argue that the static member is like a singleton inasmuch as there's only ever one in existence but that is not the true definition of a singleton class, just a side-effect of being shared among objects.
I woke up and realized I should of checked wikipedia. I was up way too late. I did not understand what it meant to be static and this article helped add to my new understanding of what it also means to be static globally and locally.
精彩评论