跟进:类方法和实例方法之间的区别?
问题描述:
这是(用户)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(说)。输出仍然没有意义。
非常感谢您的帮助。
答
您正在隐藏实例级别为numberOfPeople
的全球声明的numberOfPeople
。将其名称之一改为其他名称以避免此问题
+0
非常感谢Dan! – 2012-08-09 20:34:53
您不更改类型,而是创建新变量。 – Dustin 2012-08-09 17:22:42
非常感谢达斯汀! – 2012-08-09 20:35:52