我有一個ChatViewController,用於發送和接收消息並將消息作爲NSMutableDictionary存儲在NSArray中。當數據插入到不同源的數據源時,TableView不會重新加載
NSMutableArray *messages; //in header file
- (void)addMessage:(NSString *)receivedMessage :(NSString *) sender
{
[self reloadDataInTableView:receivedMessage :sender];
}
- (void)reloadDataInTableView:(NSString *)message :(NSString*)sender
{
NSLog(@"Text: %@ Sender: %@", message, sender);
NSMutableDictionary *m = [[NSMutableDictionary alloc] init];
[m setObject:message forKey:@"msg"];
[m setObject:sender forKey:@"sender"];
[messages addObject:m];
[self.tView reloadData];
NSLog(@"Number of rows: %d", [messages count]);
}
當我打電話從AppDelegate中「方法addMessage」,這兩個字符串傳遞,但不能將其添加到「消息」,因爲「行數」始終是零。但是當我從這個類自己存儲它時,這些消息就會被存儲並且行數會增加。
因此,它只顯示來自ChatViewController的消息,而不顯示從AppDelegate發送的消息。我希望我能夠正確地解釋這個問題。
這裏是的cellForRowAtIndexPath功能:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSMutableDictionary *s = (NSMutableDictionary *) [messages objectAtIndex:indexPath.row];
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
//cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [s objectForKey:@"msg"];
cell.detailTextLabel.text = [s objectForKey:@"sender"];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.userInteractionEnabled = NO;
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [messages count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
是,我已初始化在viewDidLoad中的消息數組。但問題是,當我試圖從AppDelegate插入到消息數組中時,計數不會增加。實際上,它總是顯示零。但是當我從ViewController本身插入時,它會保持計數。這裏是AppDelegate的代碼:
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
if ([message isChatMessageWithBody])
{
XMPPUserCoreDataStorageObject *user = [xmppRosterStorage userForJID:[message from]
xmppStream:xmppStream
managedObjectContext:[self managedObjectContext_roster]];
NSString *messageBody = [[message elementForName:@"body"] stringValue];
NSString *displayName = [user jidStr];
if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
{
ChatViewController *cvc = [[ChatViewController alloc] init];
[cvc reloadDataInTableView:messageBody :displayName];
}
else
{
// We are not active, so use a local notification instead
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.alertAction = @"Ok";
localNotification.alertBody = [NSString stringWithFormat:@"From: %@\n\n%@",displayName,messageBody];
[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
}
}
}
你的NSMutableArray初始化了嗎? – Karl
是的,你在哪裏初始化數組'messages'? – micantox
你是如何從AppDelegate發送的?給那個代碼。 – Durgaprasad