【问题标题】:Trouble with calling a method in Objective C (Apple Documentation example)在 Objective C 中调用方法时遇到问题(Apple 文档示例)
【发布时间】:2015-02-10 04:24:18
【问题描述】:

我正在关注 Apple 的“使用 Objective C 编程”文档,链接为:https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithObjects/WorkingwithObjects.html#//apple_ref/doc/uid/TP40011210-CH4-SW1

无论如何,我已经到了它要求调用 sayHello 方法的地步。

“使用alloc和init创建一个新的XYZPerson实例,然后调用sayHello方法。”

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

int main(int argc, const char * argv[]);

XYZPerson *firstPerson = [[XYZPerson alloc] init]; //Initializer element is not a lime-time constant
[firstPerson sayHello]; //No Visible @interface for 'XYZPerson' delcares the selector 'sayHello'

@implementation XYZPerson
- (void)sayHello {
    [self saySomething:@"Hello, World"];
}

- (void)saySomething: (NSString *)greeting {
    NSLog(@"%@", greeting);
}

@end

我相信我对苹果如何解释这项工作存在误解,或者只是不知道。

希望苹果完成这些示例供我们复习。

【问题讨论】:

  • 您是否按照他们所说的方式实现了 XYSperson.h 和 .m ?
  • 您的XYZPerson.m 应该main 的声明。摆脱那条线。另外,为什么@implementation 行之前有代码?该代码不得存在。
  • 这段代码在 main.m 文件中,而我也有上一章中的 XYZPerson.h 和 XYZPerson.m,为什么之前有它不好?该示例要求我在 main.m 文件中使用 allocate 和 init 创建一个实例。除非我做错了?

标签: objective-c methods


【解决方案1】:

您需要将代码放在主函数中。现在你的代码就在你的文件中,在任何函数之外。应该是:

int main(int argc, const char * argv[]) {
    XYZPerson *firstPerson = [[XYZPerson alloc] init];
    [firstPerson sayHello];
}

此外,根据文档,您应该有一个单独的 main.m 文件,其中包含您的 main 函数。

【讨论】:

  • 虽然您回答中的所有内容都是很好的信息,但它实际上并没有解决问题的实际问题,即需要在 XYZPerson 的 .h 文件中声明该方法。跨度>
  • 最初在界面中声明它并没有消除错误,但打开函数确实如此,谢谢。如果这就是您所说的,那么所有这些代码都在 main.m 文件中。
【解决方案2】:

因为您只能使用类对象访问在 .h 文件中声明的公共函数。

请在 .h 文件中声明该函数,它将解决您的问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多