【发布时间】:2019-01-23 03:12:33
【问题描述】:
我正在尝试学习如何创建类和对象以及如何在 Objective-C 中调用方法。我的小程序创建了 City 类的对象,允许命名该对象、设置年龄、人口,并获取这些值以进行打印。但是当我调用一个方法来设置这些值时,我得到一个 (null) 和零结果。这是我的代码:
城市.h
#import <Foundation/Foundation.h>
@interface City : NSObject
-(void) setName:(NSString *)theName Age:(int)theAge Population:(int)thePopulation;
-(void) getName;
-(void) getAge;
-(void) getPopulation;
-(void) nextDay;
@end
城市.m
#import "City.h"
@implementation City
{
NSString *name;
int age;
int population;
}
-(void) setName:(NSString *)theName Age:(int)theAge Population:(int)thePopulation
{
theName = name;
theAge = age;
thePopulation = population;
}
-(void) getName
{
NSLog(@"Name is %@", name);
}
-(void) getAge
{
NSLog(@"Age is %d", age);
}
-(void) getPopulation
{
NSLog(@"Population today is %d", population);
}
main.m
int main()
{
City *moscow = [[City alloc] init];
[moscow setName:@"Msk" Age:120 Population:1000];
[moscow getName];
[moscow getAge];
[moscow getPopulation];
}
运行的结果是:
Name is (null)
Age is 0
Population today is 0
Program ended with exit code: 0
我做错了什么?
【问题讨论】:
-
这看起来像是来自一个非常古老的教程的代码。现代的 ObjC 看起来不是这样的;一切都是
@propertys,getter 方法永远不会以get为前缀。同样,实例变量也很少被声明了。
标签: objective-c class methods