0

This is a followup question to (user) micmoo's response on What is the difference between class and instance methods? .

If I change the variable: numberOfPeople from static to a local variable in the class, I get numberOfPeople as 0. I have also added a line to show the numberOfPeople after the variable has been incremented each time. Just to avoid any confusion, my code is as follows:

// Diffrentiating between class method and instance method

#import <Foundation/Foundation.h>


// static int numberOfPeople = 0;

@interface MNPerson : NSObject {
    int age;  //instance variable
    int numberOfPeople;
}

+ (int)population; //class method. Returns how many people have been made.
- (id)init; //instance. Constructs object, increments numberOfPeople by one.
- (int)age; //instance. returns the person age
@end

@implementation MNPerson

int numberOfPeople = 0; 
- (id)init{

    if (self = [super init]){
        numberOfPeople++;
        NSLog(@"Number of people = %i", numberOfPeople);
        age = 0;
    }    
    return self;
}

+ (int)population{ 
    return numberOfPeople;
}

- (int)age{
    return age;
}

@end

int main(int argc, const char *argv[])
{
    @autoreleasepool {


    MNPerson *micmoo = [[MNPerson alloc] init];
    MNPerson *jon = [[MNPerson alloc] init];
    NSLog(@"Age: %d",[micmoo age]);
    NSLog(@"Number Of people: %d",[MNPerson population]);
}

}

Output:

In init block. Number of people = 1 In init block. Number of people = 1 Age: 0 Number Of people: 0

Case 2: If you change the numberOfPeople in the implementation to 5 (say). The output still does not make sense.

Thank you in advance for your help.

Community
  • 1
  • 1
Rutvij Kotecha
  • 935
  • 2
  • 10
  • 21

1 Answers1

2

You are hiding the globally declared numberOfPeople with the instance level numberOfPeople. Change one of their names to something else to avoid this problem

Dan F
  • 17,654
  • 5
  • 72
  • 110