My UITableView
contains messages (a message has a text and an image). At the beginning, my UITableView
is empty:
@property (strong, nonatomic) NSMutableArray *messages; @property (strong, nonatomic) IBOutlet UITableView* tableView; - (void)viewDidLoad{ self.messages = [[NSMutableArray alloc] init]; }
The UITableViewDelegate
, and UITableViewDataSource
is connected in the IB. When I get a message, I want to show it on the UITableView
as follow:
- (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]; }
At this point, my Messages mutable array contains exactly the message. However, when reloading the UITableView
, the message seems to point to another address.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ Message *message = [self.messages objectAtIndex:indexPath.row]; cell.textLabel.text = message.text; cell.imageView.image = [message getImage]; }
the message is not nil, but message.text is nil. I doubt that the userInfo is release when getting out of function didReceiveMessage
. So, that's why the message is not nil, but point to an address that contains nothing. What I tried to do is retain or copy the message before adding it to the NSMutableArray
messages like:
- (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]; }
But I am afraid that doing such thing will make the program to be leak. Do you have any solution? Or explain me why?
More info:
my Message class looks like this:
@interface Message : NSObject @property (nonatomic, assign) NSString *text; @end
Do I need to change it to @property (nonatomic, retain) NSString* text; ????