2012-08-09 100 views
0

這是(用戶)micmoo對What is the difference between class and instance methods?的迴應的後續問題。跟進:類方法和實例方法之間的區別?

如果我將變量numberOfPeople從靜態更改爲類中的局部變量,我將numberOfPeople設置爲0.我還在每次增加變量後添加了一行以顯示numberOfPeople。只是爲了避免任何混亂,我的代碼如下:

// 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]); 
} 

} 

輸出:

在初始塊。人數= 1在init塊中。人數= 1年齡:0人數:0

案例2:如果您將執行中的numberOfPeople更改爲5(說)。輸出仍然沒有意義。

非常感謝您的幫助。

+0

您不更改類型,而是創建新變量。 – Dustin 2012-08-09 17:22:42

+0

非常感謝達斯汀! – 2012-08-09 20:35:52

回答

2

您正在隱藏實例級別爲numberOfPeople的全球聲明的numberOfPeople。將其名稱之一改爲其他名稱以避免此問題

+0

非常感謝Dan! – 2012-08-09 20:34:53

相關問題