【问题标题】:Adding data dynamically in UITableView在 UITableView 中动态添加数据
【发布时间】:2014-07-15 01:29:41
【问题描述】:

我的UITableView 包含消息(消息包含文本和图像)。一开始我的UITableView是空的:

@property(强,非原子)NSMutableArray *messages; @property(强,非原子)IBOutlet UITableView* tableView; - (void)viewDidLoad{ self.messages = [[NSMutableArray alloc] init]; }

UITableViewDelegateUITableViewDataSource 在 IB 中连接。当我收到一条消息时,我想在UITableView 上显示如下:

- (void)didReceiveMessage:(NSNotification *) 通知{ //- 提取消息 NSDictionary* userInfo = notification.userInfo; 消息* msg = [userInfo objectForKey:kNotificationMessage]; //- 更新表 [self.messages addObject:msg]; [self.tableView reloadData]; [自scrollTableViewToBottom]; }

此时,我的 Messages 可变数组正好包含消息。但是,当重新加载UITableView 时,该消息似乎指向另一个地址。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 消息 *message = [self.messages objectAtIndex:indexPath.row]; cell.textLabel.text = message.text; cell.imageView.image = [消息获取图像]; }

message 不是 nil,但 message.text 是 nil。我怀疑在退出功能didReceiveMessage 时会释放 userInfo。所以,这就是为什么消息不是零,而是指向一个不包含任何内容的地址。我尝试做的是在将消息添加到NSMutableArray 消息之前保留或复制消息,例如:

- (void)didReceiveMessage:(NSNotification *) 通知{ //- 提取消息 NSDictionary* userInfo = notification.userInfo; 消息* msg = [userInfo objectForKey:kNotificationMessage]; 消息* copyMsg = [消息复制]; //- 更新表 [self.messages addObject:copyMsg]; [self.tableView reloadData]; [自scrollTableViewToBottom]; }

但我担心这样做会导致程序泄漏。你有什么解决办法吗?或者解释一下为什么?

更多信息:

我的 Message 类如下所示:

@interface 消息:NSObject @property (nonatomic, assign) NSString *text; @结尾

我需要把它改成@property (nonatomic, retain) NSString* text; ???

【问题讨论】:

  • 其余代码在哪里?
  • 将文本和图像添加到不同的数组中,然后使用 tableView 委托方法将它们显示在表格中
  • 我在发布问题时遇到了一些与文本格式相关的问题。虽然问题没有完成,但你可以回答它。我真的很佩服你。 :-)
  • 你使用ARC吗?还有,如何在 Message 对象中声明文本变量(强、非原子)?
  • 我想我使用 ARC。这是XCODE5、iOS7的默认设置,我什么都没改

标签: ios objective-c uitableview


【解决方案1】:

Message 对象中,声明文本变量:

@property (nonatomic, assign) NSString *text

这就是为什么text在你得到它的价值时为零的根本原因。如果你设置值

NSString *s = @"SomeValue"; Message.text=s;

s variable 在那之后被释放,你的文本也将被释放。因此,您应该声明 text 变量为 strong 以保持其值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 2020-06-03
    • 2011-12-05
    • 1970-01-01
    • 2017-05-12
    相关资源
    最近更新 更多