0

我有一个名为 person 的类,有两个值:年龄和体重。为什么我不能像这样在主函数中访问这两个值:

int a=[chuck age]; int b=[chuck weight];

最好的方法是什么?使用属性是正确的方法吗?

头文件:

#import <Foundation/Foundation.h>
    @interface person : NSObject
    {
        int age;
        int weight;
    }
    -(void) print;
    -(void) setAge;
    -(void) setWeight;

@end

实现文件:

#import "person.h"

@implementation person

-(void) print
{
    printf("Your age is %d and your weight is %d.", age, weight);
}

-(void) setAge
{
    printf("Write age: ");
    int v;
    scanf("%d", &v);
    age=v;
}

-(void) setWeight
{
    printf("Write weight: ");
    int g;
    scanf("%d", &g);
    weight=g;
}

@end
4

3 回答 3

8

您是否正在使用某种教程或书籍?这是学习编写 OS X 或 iOS 应用程序的一个奇怪的起点。

无论如何,问题在于您已经将 getter/setter 的东西与实现其他功能的方法串通了起来。

我建议将您的Person课程声明为:

 @interface Person : NSObject
 @property NSInteger age;
 @property NSInteger weight;
 @end

使用 Person.m:

 @implementation Person
 - (id) init {
     self = [super init];
     if (self) {
          // preposterous initial values so we know if they weren't set.
          _age = -1;
          _weight = -1; 
     }
     return self;
 }
 @end

也就是说,aPerson仅保存有关单个人的信息。它不执行任何类型的 I/O 等...

然后,您的 main.m 看起来像:

#import <Foundation/Foundation.h>
#import "Person.h"

NSInteger ScanIntegerWithPrompt(NSString *prompt) {
    printf("%s: ", [prompt UTF8String]);
    int v;
    scanf("%d", &v);
    return (NSInteger) v;
}

int main(...) {
    @autoreleasepool {
      Person *p = [[Person alloc] init];
      p.age = ScanIntegerWithPrompt(@"Enter age:");
      p.weight = ScanIntegerWithPrompt(@"Enter weight:");
      printf("Your age is %d and your weight is %d", p.age, p.weight);
    }
    return 0;
}

以这种方式构建代码将模型(数据容器)与控制层分开。这里没有太多的视图层。

如果您真的想将 I/O / 解析逻辑与Person对象一起保留,请在 Person 对象中添加如下内容:

...
- (NSNumber)readIntegerWithPrompt:(NSString*)prompt
{
    ... same code as function above ...
}

- (void)readAgeFromStandardInput
{
   self.age = [self readIntegerWithPrompt:@"Enter age: "];
}

- (void)readWeightFromStandardInput
{
   self.weight = [self readIntegerWithPrompt:@"Enter weight: "];
}
...

然后你会从你的main.

于 2013-07-13T16:07:45.620 回答
2

您的问题是您正在尝试访问 privateageweightivars,这是无法通过这种方式访问​​的。

执行此操作的好方法是使用 ObjC 属性,但这不是您的示例所必需的。

您需要创建两个方法来访问私有 ivars,调用它们ageweight,它们在类接口中应该如下所示:

- (int) age;
- (int) weight;

实施是:

- (int) age{
   return age;
}

- (int) weight{
   return weight;
}

现在在您的 main.m 中,您可以像这样轻松访问所需的数据:

#import <Foundation/Foundation.h>
#import "person.h"
int main(int argc, char *argV[]) {
    @autoreleasepool {
        person *andrew = [[person alloc]init];
        [andrew setAge];
        [andrew setWeight];
        NSLog(@"Age:%d, Weight:%d",[andrew age], [andrew weight]);
    }
return 0;
}

如果您想知道它是如何处理属性的,请告诉我,我可以更新答案:)

于 2013-07-13T15:42:24.000 回答
0

在您的头文件中:

@property int age;
@property int weight;
于 2013-07-13T15:20:39.547 回答