[英]Global Functions Objective C
我正在尝试编写全局函数,但是在尝试调用它时,始终出现错误“无可见接口...。”。
弹出窗口
#import <Foundation/Foundation.h>
@interface Popover : NSObject{}
- (void)PopoverPlay;
@end
Popover.m
#import "Popover.h"
@implementation Popover
- (void)PopoverPlay{
NSLog(@"I Work");
}
@end
在View.mi中添加导入“ Popover.h”,但是当我尝试运行时我无法摆脱错误消息。
#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];
}
任何想法谢谢
您显示的代码是包含单个实例方法的类的声明和定义。 要使用它,您需要分配一个Popover
实例,其代码如下所示:
#import "Popover.h"
//...
Popover *pop = [[Popover alloc] init];
[pop PopoverPlay];
//...
当人们谈论“全局函数”时,它们通常不是指实例方法(甚至是类方法),因此我怀疑这正是您所追求的。 也许您的意思是可以从代码的其他部分调用的实际功能? 您将以与在C中相同的方式进行操作:
void foo(void);
void foo(void)
{
NSLog(@"This works");
}
如果将原型(第一行)添加到头文件中,则可以在包含该头文件的任何文件中的任何位置使用该函数。
更新:
- (IBAction)ButtonPress {
[self PopoverPlay];
}
这里的问题是您-PopoverPlay
self
发送-PopoverPlay
,但是在这种情况下, self
表示View
的实例。 您需要将-PopoverPlay
发送到实现它的类的实例,即Popover
。 参见上面的示例。 (顺便说一句,您的界面和实现不匹配:一个是PupilView
,另一个是View
。)
要调用您编写的方法,您需要执行以下操作:
Popover *myPopover = [[Popover alloc] init];
[myPopover PopoverPlay];
您拥有的是一个实例方法。 因为您的方法不依赖任何实例变量,所以可以通过将-
更改为+
使其成为类方法:
+ (void)PopoverPlay;
和
+ (void)PopoverPlay{
然后,您无需初始化新的Popover
; 您可以致电:
[Popover PopoverPlay];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.