これは、クラス メソッドとインスタンス メソッドの違いは何ですか?に関する (ユーザー) micmoo の回答に対するフォローアップの質問です。.
変数 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 に変更した場合 (たとえば)。出力はまだ意味がありません。
よろしくお願いいたします。