我有一个 ChatViewController,我在其中发送和接收消息,并将消息作为 NSMutableDictionary 存储在 NSArray 中。
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];
}
}
}