2012-02-13 67 views
1

調用選擇在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錯誤。 你能幫我嗎?謝謝。

回答

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 

當你創建的類文件,設置冷杉信大,像爲「Allerta」。

+0

Thanks Infog。我需要[_allerta發佈];在OSX中? – Joannes 2012-02-13 15:22:13

+0

然後,您爲對象創建分配內存(alloc,copy,new),您需要爲對象創建釋放,而不需要該對象。您需要閱讀有關Objective-C開發的更多信息。 – alexmorhun 2012-02-13 16:06:58

+0

你可以將'allerta * _allerta = [allerta alloc];'改成'* _allerta = [[allerta alloc] autorelease];'然後你不需要寫'[_allerta release];' – alexmorhun 2012-02-13 16:08:09

0

我認爲你的問題是,當AppDelegate沒有聲明這個方法時,你聲明AppDelegate爲alerticonstatus消息的接收者。你在這行做這個:

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

你的解決辦法是從self在這種情況下是AppDelegate的一些allerta對象更改的觀察員。只需alloc-init一些allerta對象並將其添加爲觀察者。