Class variable defined at @implementation rather than @interface?

后端 未结 6 2072
夕颜
夕颜 2020-11-29 02:46

I\'m new to Objective-C, but I am curious about something that I haven\'t really seen addressed anywhere else.

Could anyone tell me what is the difference between a

6条回答
  •  星月不相逢
    2020-11-29 03:40

    They're very different! The one in @implementation is a global variable not unique to each instance. Imagine there were accessors for both variables, written in the obvious way. Then the difference in behavior is shown here:

    Someclass* firstObject = [[Someclass alloc] init];
    Someclass* secondObject = [[Someclass alloc] init];
    
    //forExample is an instance variable, and is unique to each instance.
    [firstObject setForExample:@"One"];
    [secondObject setForExample:@"Two"];
    NSLog(@"%@",[firstObject forExample]); //Result: "One"
    NSLog(@"%@",[secondObject forExample]); //Result: "Two"
    
    //anotherExample is a global variable, and is NOT unique to each instance.
    [firstObject setAnotherExample:@"One"];
    [secondObject setAnotherExample:@"Two"];
    NSLog(@"%@",[firstObject anotherExample]); //Result: "Two" (!)
    NSLog(@"%@",[secondObject anotherExample]); //Result: "Two"
    
    //Both instances return "Two" because there is only ONE variable this time.
    //When secondObject set it, it replaced the value that firstObject set.
    

    If you are looking for this sort of behavior, you might be better off using a class variable, like this:

    static NSString* yetAnotherExample = nil;
    

    Then you can use class methods to interact with the variable, and it's clearly class-specific (as opposed to instance-specific or global).

提交回复
热议问题