2012-06-15 7 views
1

У меня есть два класса, класс A и класс B. Класс A имеет миссию, не связанную с чатом, но ей нужно реагировать на получение сообщения чата. Когда приходит сообщение, оно хранится в NSMutableDictionary, являющемся этим словарем, хранящимся в NSMutableArray. Если полученное сообщение является первым ([array count] == ​​1), отображается представление класса B, представляющее UITableView, данные которого заполняются массивом. Все работает отлично для более ясного сообщения.Чат и UITable

Пришло второе сообщение. Новое сообщение добавляется в массив (это делается в классе A), но таблица не заполняется. Как я мог достичь этой цели?

Код:

Класс

- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message 
{ 
NSString *msg = [[message elementForName:@"body"] stringValue]; 
NSString *from = [[message attributeForName:@"from"] stringValue]; 

NSMutableDictionary *m = [[NSMutableDictionary alloc] init]; 
[m setObject:msg forKey:@"msg"]; 
[m setObject:from forKey:@"sender"]; 
[messarray addObject:m]; 


[self newMessageReceived:messarray]; 
} 

- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender 
{ 
NSLog(@"Method xmppStreamDidAuthenticate"); 
[self goOnline]; 
} 

//- (void) newMessageReceived:(NSMutableDictionary *)message 
-(void) newMessageReceived:(NSMutableArray *)messarraylocal 
{ 
General *general = [General sharedManager];//An static class to store settings like username, and other things that must be available in the hole app. 
general.numcels++; 
general.messarray=messarraylocal; 
    // NSString *firstmessage=[message objectForKey:@"msg"]; 
//NSString *from=[message objectForKey:@"sender"];  
//NSArray *listItems = [from componentsSeparatedByString:@"@"]; 
//NSString *fromsplit=[listItems objectAtIndex:0]; 
//general.firstmess=firstmessage; 
//general.firstfrom=fromsplit; 




if ([messarraylocal count]==1){ 
ChatViewController *cvc=[[ChatViewController alloc]initWithNibName:@"Chat" bundle:nil]; 

[[self navigationController]pushViewController:cvc animated:YES]; 

} 
} 

Класс B:

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
General *general = [General sharedManager]; 
NSLog(@"We are in numberOfRowsInSection, de ChatViewController"); 
return general.messarray.count; 
} 

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
General *general = [General sharedManager]; 

NSLog(@"We are in cellForRowAtIndexPath de ChatViewController"); 
//UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"]; 
//if(!cell){ 
messarray=general.messarray; 
for (int i=0;i<messarray.count; i++) 
{ 
    diccio=[messarray objectAtIndex:i]; 
    general.firstmess=[diccio objectForKey:@"msg"]; 
    general.firstfrom=[diccio objectForKey:@"sender"]; 

UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"UITableViewCell"]; 
//} 
text=general.firstmess; 
remite=general.firstfrom; 
[[cell textLabel]setText:remite]; 
[[cell detailTextLabel] setText:text]; 

return cell; 

} 
} 

- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message 
{ 
NSString *msg = [[message elementForName:@"body"] stringValue]; 
NSString *from = [[message attributeForName:@"from"] stringValue]; 
NSLog(@"We are in didReceiveMessage of ChatViewController"); 
NSMutableDictionary *m = [[NSMutableDictionary alloc] init]; 
[m setObject:msg forKey:@"msg"]; 
[m setObject:from forKey:@"sender"]; 


[self newMessageReceived:m]; 
} 

- (void) newMessageReceived: (NSMutableDictionary *) message// this method is NEVER called 
{ 
General *general = [General sharedManager]; 
general.numcels++; 
NSLog(@"numcels vale %i", general.numcels); 
NSString *firstmessage=[message objectForKey:@"msg"]; 
NSString *from=[message objectForKey:@"sender"];  
NSArray *listItems = [from componentsSeparatedByString:@"@"]; 
NSString *fromsplit=[listItems objectAtIndex:0]; 
general.firstmess=firstmessage; 
general.firstfrom=fromsplit; 
NSLog(@"Message receive in ChatViewController: %@ from %@", [message objectForKey:@"msg"], fromsplit); 

} 

В методе didViewLoad класса B, я:

table.delegate=self; 
table.dataSource=self; 

Но безрезультатно. Я знаю, что [table reload] может работать, но ... где я могу это сделать?

Кто-нибудь может мне помочь? Спасибо!

ответ

0

В классе А newMessageReceived после добавления нового сообщения в глобальную messarray

Вам нужно будет уволить NSNotification

-(void) newMessageReceived:(NSMutableArray *)messarraylocal 
{ 
    //in addition to your normal code, add the following 
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NewMessage" object:nil]; 
} 

В настоящее время в регистре класса B для наблюдения

- (void) viewDidLoad 
{ 
    //In addition to your normal code here add the following 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newMessage) name:@"NewMessage" object:nil]; 
} 

//Add this method that will call reload data 
- (void) newMessage 
{ 
    [table reloadData]; 
} 
+0

Омар им просто о выходе из работы и, возможно, у меня не будет времени, чтобы проверить ваше решение, но я обещаю, что если я в понедельник проверить и он работает, я отвечу на ваш ответ. Но даже если это не работает, большое спасибо за то, что потратили время, пытаясь помочь :) – Fustigador

+0

его всегда приятно помочь :) –

+1

Я пробовал, Омар, и он вызывает reloadData. Но это не работает правильно. Он возвращает одну и ту же ячейку и никогда не возвращает вторую в массиве. Но ваш ответ был верным. Еще раз спасибо! – Fustigador

0

Вы сохраняете предыдущее сообщение в своем массиве ... , если нет, то в вашем didReceiveMessage: поставить одну строку перед добавлением объекта в массиве ...

[messarray removeAllObjects]; 
+0

Да, я их храню. – Fustigador

Смежные вопросы