【问题标题】:How To Call Methods In Objective-C如何在 Objective-C 中调用方法
【发布时间】:2014-10-24 13:31:56
【问题描述】:

我在一个相当简单的脚本中调用方法时遇到问题。

由于某种原因,当我运行程序时,我在控制台中得到的只是返回 0。

我能做些什么来解决它?这是我的脚本:

#import <Foundation/Foundation.h>

@interface person:NSObject {
    int weight;
    int height;
    int age;
}

- (void)printtoscreen;
- (void)setweight:(int)w;
- (void)setheight:(int)h;
- (void)setage:(int)a;

@end

@implementation person

-(void) printtoscreen {   
    NSLog(@"I am %i years old, I weigh %i pounds, and I am %i feet tall", age, weight, height);
}

- (void)setweight:(int)w {
    w=weight; 
}

- (void)setheight:(int)h {
    h=height;
}

- (void)setage:(int)a {
    a=age; 
}

@end

int main(int argc, const char * argv[]) {
   @autoreleasepool {
       person *bob;
       [bob setweight:150];
       [bob setheight:5];
       [bob setage:25];
       [bob printtoscreen];
    }

    return 0;
}

【问题讨论】:

    标签: objective-c variables object methods console


    【解决方案1】:

    最大的问题是我们从来没有真正创建过对象,所以我们所有的消息都发送到nil

    您必须做的第一个也是最直接的修复实际上是实例化对象:

    person *bob = [[person alloc] init];
    

    这必须在我们的任何方法实际调用对象之前完成。

    现在,我们必须修复 Jens 提到的方法。我们的任务倒退了。参数应该是右值,实例变量应该是左值:

    - (void)setweight:(int)w {
        weight = w;
    }
    

    通过这两个修复,一切都应该正常工作。

    【讨论】:

    • 问题中的代码也存在一些样式和OOP问题。我假设这个提问者是在编程课的第一周左右,所以我选择不提及他们,因为它可能会混淆并分散实际问题的注意力。
    【解决方案2】:

    你的二传手完全错了:

    -(void) setweight: (int) w {
    w=weight;
    }
    

    应该是:

    -(void) setweight: (int) w {
    weight = w; 
    }
    

    其他二传手以此类推

    【讨论】:

    • 这只是问题的一部分。
    • @nhgrif 你对这条评论有什么看法?请解释您的反对意见。
    • 看我的回答。如果这是唯一的问题,我们会在日志中看到:I am 0 years old, I weigh 0 pounds, and I am 0 feet tall(或者可能是一些随机数......我不记得了......但 something 会打印)跨度>
    猜你喜欢
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    相关资源
    最近更新 更多