开发者

initWithCoder and initWithNibName

开发者 https://www.devze.com 2022-12-28 06:09 出处:网络
I am trying to encode some data state in a UITableViewController. In the first time, I init the object with Nibname without any problem. However, when I initWithCoder, the UITableViewController still

I am trying to encode some data state in a UITableViewController. In the first time, I init the object with Nibname without any problem. However, when I initWithCoder, the UITableViewController still loads but when I clicked on a cell, the application crash and the debugger tells me about EXEC_BAD_ACCESS, something wrong with my memory, but I do not know

Here is my code:

- (id) init {
    if(self = [self initWithNibName:@"DateTableViewController" bundle:nil]) {        
        self.dataArray = [[NSMutableArray alloc] initWithObjects:@"1", @"2", @"3", nil];
    }
    return self;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableVie开发者_如何学Cw:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Set up the cell...
    int index = indexPath.row;
 cell.textLabel.text = [self.dataArray objectAtIndex:index];;
    return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    return @"Test Archiver";
}
- (void)encodeWithCoder:(NSCoder *)coder {
    [super encodeWithCoder:coder];
    [coder encodeObject:self.dataArray];
}
- (id)initWithCoder:(NSCoder *)coder {
 return [self init];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    int index = indexPath.row;
    [self.dataArray addObject:[NSString stringWithFormat:@"Hello %d", index]];
    [self.tableView reloadData];
}


I see two problems here:

1) You are serializing your dataArray using encodeObject: but omit to deserialize it in initWithCoder:

2) You should rather use NSKeyedArchiver's method encodeObject:forKey:. Then you are free to use the serialized information in the decoding or not.

Other than that I can only say to answer your question it would be helpful to include information about where the crash happens.


There is only one memory problem in this code: In init you are leaking the NSMutableArray. But that’s kind of the opposite problem you are looking for. The bug you described is not in the posted code.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号