2013-06-24 47 views
0

我有一個類A(監聽器),在他的init方法觀察了通知和實例化和膨脹一個NSMutableArraypostNotification訪問觀察者

的不同實例當類B(發件人)訊息至觀察者的通知的類, 它正確地調用方法內的選擇器中聲明的方法我的實例變量NSMutableArray指向0x000000

可能通知運行在一個不同的istance類?我可以解決買聲明作爲一個Singleton

@implementation ClassA 
@synthesize myArray; 

-(id) init { 
    if (self = [super init]){ 
    [[NSNotificationCenter defaultCenter] addObserver:self 
               selector:@selector(methodThatGetsCalled:) 
                name:@"dispatchMethods" 
                object:nil]; 

     classB = [[ClassB alloc] init]; 

    } 
    return self; 
} 

- (void)anotherClassAMethod { 
    // first i populate my array 
    myArray = [[NSMutableArray alloc] initWithArray:eventsArray]; 
    // than i call Class B 
} 
- (void)methodThatGetsCalled:(NSNotification)note { 
    // when the notification is posted, this method gets called but... 
    myArray; //points to 0x000000 here 
} 
+0

實例化之前打到methodThatGetsCalled:您可以發佈您的init方法嗎? – yonosoytu

+0

也許你錯過了這個變量。讓我們看看一些代碼! – Groot

+0

完成,最乾淨的可能 – Zerho

回答

0

你所說的這裏是......

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

任何時候任何人(它不事誰)呼喊"dispatchMethods"所有ClassA火的情況下methodThatGetsCalled:

所以你想要更有選擇性,只有在特定的實例發佈時才能進行監聽。

classB = [[ClassB alloc] init]; 

[[NSNotificationCenter defaultCenter] addObserver:self 
               selector:@selector(methodThatGetsCalled:) 
                name:@"dispatchMethods" 
                object:classB]; 

在這種情況下,你只會聽到通知,如果classB是發佈對象中,當您從classB

[[NSNotificationCenter defaultCenter] postNotificationName:@"dispatchMethods" object:self userInfo:nilOrWhatever] 

所以後,如果你有ClassAClassB您選擇的多個實例完全正確的另一個實例在anotherClassAMethod

+0

我讓觀察者「打開」到其他類沒有問題, 我的問題是當postNotification之後的方法被調用時,確實,它無法訪問NSarray中的日期,我確定在那裏。 實際上,聲明變量Global到al的實例它似乎工作,但它看起來不是正確的方式, 回到我的第一點,通知以某種靜態方式調用類或使另一個實例? – Zerho