iphone - 从 objective-c 中的方法返回一个整数

标签 iphone objective-c ios

我在弄清楚如何简单地从方法返回整数时遇到问题。

这是我的:

简单.h

@interface simple : NSObject {
}
- (int)simpleMethod;
@end

简单.m

#import "simple.h"
@implementation simple
- (int)simpleMethod {
    return 0;
}
@end

simpleViewController.m

- (IBAction)simpleButtonPressed:(id)sender {
    int test = [simple simpleMethod];
}

我在“int test...”行收到警告,“simple 可能不会响应‘+simpleMethod’”。另一个警告说,“初始化从指针生成整数而不进行强制转换”。

我的程序在这一行崩溃了,所以虽然这只是一个警告,但它似乎是一个问题。

我希望能够在不创建类“simple”的实例的情况下使用“simpleMethod”。这可能吗?

问题已解决:根据 Peter 的建议将 - 更改为 +。

最佳答案

当前您将 simpleMethod 定义为实例方法。但是要做你想做的,你需要将方法定义为类方法:

@interface simple : NSObject {
}
+ (int)simpleMethod;
@end

#import "simple.h"
@implementation simple
+ (int)simpleMethod {
    return 0;
}
@end

- (IBAction)simpleButtonPressed:(id)sender {
    int test = [simple simpleMethod];
}

注意方法定义上的“+”

还有错别字(?),你有 queryDatabase 的类定义,但是 simple 的类实现

关于iphone - 从 objective-c 中的方法返回一个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9286923/

相关文章:

iphone - 动画 UIImageView 色调

ios - 如何向 EKEvent 添加一些附加字段

objective-c - 应用图标问题上的远程通知角标(Badge)

ios - 添加 Google map 作为 subview 无限调用 viewDidLoad()

iphone - 如何从通过 NSthread 调用的函数中获取返回值?

ios - 多个 XIB 错误 : Could not load NIB in bundle

iphone - 带有 NSDictionary 的 UIPickerView

ios - UIPickerView 选择行不起作用 ios7

ios - 从父 View 向容器 View 传递数据

ios - 子类化 UIView。 init 方法永远不会被调用