Reputation: 27
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
- (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'". 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". Is this possible?
Problem fixed: changed the - to a + as per Peter's suggestion.
Upvotes: 0
Views: 4631
Reputation: 1414
You may want to use NSInteger. They are the same thing, but I believe it's more correct formatting wise(since I see you are interacting with a 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. As Josh pointed out below you can use self, but it points to the class, not an instance of it.
+ 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];
}
Upvotes: 0
Reputation: 7513
Currently you have simpleMethod defined as an instance method. 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
Upvotes: 6