从多个文件中调用选择器

时间:2012-02-13 14:34:08

标签: objective-c xcode selector nsnotifications

在AppDelegate.m中,我已经定义了

#import "AppDelegate.h"
#import "allerta.h"

@implementation AppDelegate
@synthesize window = _window;

-(void)awakeFromNib {

// Add an observer that will respond to loginComplete
[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(alerticonstatus:) 
                                             name:@"alert" object:nil];

// Post a notification to loginComplete
[[NSNotificationCenter defaultCenter] postNotificationName:@"alert" object:nil];
}
@end

我想从allerta.h打电话给 alerticonstatus

#import <Foundation/Foundation.h>
@interface allerta : NSObject{
}

-(void)alerticonstatus:(NSNotification *)note;

@end

allerta.m:

#import "allerta.h"
@implementation allerta

-(void)alerticonstatus:(NSNotification *)note {

NSLog(@"called alerticonstatus");

}
@end

我可以从allerta.h这样的另一个文件中导入函数whit @selector吗? 现在我有SIGABRT错误。 你能帮助我吗?感谢。

2 个答案:

答案 0 :(得分:1)

改变你的方法,它起作用:

#import "AppDelegate.h"
#import "allerta.h"

@implementation AppDelegate
@synthesize window = _window;

-(void)awakeFromNib {
   allerta *_allerta = [allerta alloc]; //allocation memory

   // Add an observer that will respond to loginComplete
   [[NSNotificationCenter defaultCenter] addObserver:_allerta //here you called self, but you need to call your class allerta
                                         selector:@selector(alerticonstatus:) 
                                             name:@"alert" object:nil];
    [_allerta release]; //kill _allerta class if you don't need more

    // Post a notification to loginComplete
    [[NSNotificationCenter defaultCenter] postNotificationName:@"alert" object:nil];
}
@end

创建类文件时,将firs letter设置为big,如“Allerta”。

答案 1 :(得分:0)

我认为您的问题是,当AppDelegate没有声明此方法时,您将AppDelegate声明为alerticonstatus消息的接收者。你正在这行:

[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(alerticonstatus:) 
                                             name:@"alert" object:nil];

您的解决方案是将观察者从self更改为某些allerta对象,在这种情况下是AppDelegate。只需alloc-init一些allerta对象并将其添加为观察者。

相关问题