简体   繁体   English

从Objective-C中的方法返回整数

[英]returning an integer from a method in objective-c

I am having a problem figuring out how to simply return an integer from a method. 我在弄清楚如何简单地从方法返回整数时遇到问题。

Here is what I have: 这是我所拥有的:

simple.h 简单的

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

simple.m 简单的

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

simpleViewController.m simpleViewController.m

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

I am getting a warning on the line "int test..." that says, "simple may not respond to '+simpleMethod'". 我在“ int test ...”行上收到一条警告,提示“简单可能不会响应'+ simpleMethod'”。 And another warning that says, "Initialization makes integer from pointer without cast". 另一个警告说,“初始化不使用强制转换就从指针生成整数”。

My program is crashing on this line, so although this is just a warning it seems to be a problem. 我的程序在此行崩溃,因此尽管这只是一个警告,但似乎是一个问题。

I want to be able to use "simpleMethod" without creating an instance of the class "simple". 我希望能够使用“ simpleMethod”而不创建类“ simple”的实例。 Is this possible? 这可能吗?

Problem fixed: changed the - to a + as per Peter's suggestion. 已解决的问题:根据Peter的建议,将-更改为+。

Currently you have simpleMethod defined as an instance method. 当前,您已经将simpleMethod定义为实例方法。 But to do what you want to do, you need to define the method as a class method: 但是要做您想做的事,您需要将方法定义为类方法:

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

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

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

Note the "+" on the method definition 注意方法定义上的“ +”

Also the typo(?) where you had the class definition of queryDatabase , but the class implementation of simple 还有typo(?),其中您具有queryDatabase的类定义,但是simple的类实现

You may want to use NSInteger. 您可能要使用NSInteger。 They are the same thing, but I believe it's more correct formatting wise(since I see you are interacting with a UIViewController). 它们是同一回事,但是我认为这是更正确的格式化方法(因为我看到您正在与UIViewController进行交互)。

Also it's important to note that you will not be able to access instance methods with self in class methods, because obviously there is no instance for self to point to. 同样要注意的是,您将无法使用self in class方法访问实例方法,因为显然没有self可以指向的实例。 As Josh pointed out below you can use self, but it points to the class, not an instance of it. 正如Josh在下面指出的那样,您可以使用self,但是它指向的是类,而不是它的实例。

+ symbol is a class method +符号是一个类方法

- is an instance method. -是实例方法。

@interface Simple : NSObject 
+ (NSInteger)simpleMethod;
@end

#import "Simple.h"
@implementation Simple

+ (NSInteger)simpleMethod 
{
   return 0;
}
@end

- (IBAction)simpleButtonPressed:(UIButton *)sender
{
   NSInteger test = [simple simpleMethod];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM