gpt4 book ai didi

ios - 在 UITableView 中动态添加数据

转载 作者:行者123 更新时间:2023-11-29 02:56:19 26 4
gpt4 key购买 nike

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

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

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

- (void)didReceiveMessage:(NSNotification *) notification{    //- extract message    NSDictionary* userInfo = notification.userInfo;    Message* msg = [userInfo objectForKey:kNotificationMessage];    //- update table    [self.messages addObject:msg];    [self.tableView reloadData];    [self scrollTableViewToBottom];}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{       Message *message = [self.messages objectAtIndex:indexPath.row];         cell.textLabel.text = message.text;    cell.imageView.image = [message getImage];}

消息不是nil,但是message.text是nil。我怀疑退出函数 didReceiveMessage 时 userInfo 是否被释放。所以,这就是为什么该消息不是 nil,而是指向一个不包含任何内容的地址。我尝试做的是保留或复制消息,然后将其添加到 NSMutableArray 消息中,例如:

- (void)didReceiveMessage:(NSNotification *) notification{    //- extract message    NSDictionary* userInfo = notification.userInfo;    Message* msg = [userInfo objectForKey:kNotificationMessage];    Message* copyMsg = [msg copy];    //- update table    [self.messages addObject:copyMsg];    [self.tableView reloadData];    [self scrollTableViewToBottom];}

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

更多信息:

我的消息类如下所示:

@interface Message : NSObject@property (nonatomic, assign) NSString *text;@end

我需要将其更改为@property(非原子,保留)NSString*文本吗? ????

最佳答案

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

@property (nonatomic, assign) NSString *text

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

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

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

关于ios - 在 UITableView 中动态添加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23867328/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com