user2461593
user2461593

Reputation: 87

Global Functions Objective C

I am trying to write a global function however keep getting the error "No visible interface...." when i try and call it.

Popover.h

#import <Foundation/Foundation.h>

@interface Popover : NSObject{}

- (void)PopoverPlay;

@end

Popover.m

#import "Popover.h"

@implementation Popover

- (void)PopoverPlay{
     NSLog(@"I Work");
}

@end

In View.m i am adding the import "Popover.h" but i cant get rid of the error message when i try and run.

#import "View.h" 
#import <QuartzCore/QuartzCore.h>
#import "Popover.h"

@interface View ()
{
}
@end

@implementation View

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    // Custom initialization

    }
    return self;
}
- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}

- (void)viewDidLoad{
    [super viewDidLoad];
}

- (IBAction)ButtonPress {
    [self PopoverPlay];
}

Any ideas Thanks

Upvotes: 0

Views: 1234

Answers (2)

Caleb
Caleb

Reputation: 125007

The code you've shown is the declaration and definition of a class that contains a single instance method. To use it, you'll need to allocate an instance of Popover with code that looks something like:

#import "Popover.h"

//...
Popover *pop = [[Popover alloc] init];
[pop PopoverPlay];
//...

When people talk about "global functions" they don't usually mean instance methods (or even class methods), so I doubt this is quite what you're after. Perhaps you mean an actual function that you can call from other parts of your code? You'd do that the same way you do in C:

void foo(void);

void foo(void)
{
    NSLog(@"This works");
}

If you add the prototype (first line) to a header file, you can use the function anywhere in any file that includes that header.

Update:

- (IBAction)ButtonPress {
    [self PopoverPlay];
}

The problem here is that you're sending -PopoverPlay to self, but self in this case represents an instance of View. You need to send -PopoverPlay to an instance of the class that implements it, which is Popover. See my example above. (BTW, your interface and implementation don't match: one is PupilView and the other is View.)

Upvotes: 3

Aaron Brager
Aaron Brager

Reputation: 66252

To call the method you wrote, you need to do something like:

Popover *myPopover = [[Popover alloc] init];
[myPopover PopoverPlay];

What you have is an instance method. Because your method doesn't rely on any instance variables, you could make it a class method by changing the - to +:

+ (void)PopoverPlay;

and

+ (void)PopoverPlay{

Then you don't need to initialize a new Popover; you can just call:

[Popover PopoverPlay];

Upvotes: 0

Related Questions