initWithCoder and initWithNibName

Posted by vodkhang on Stack Overflow See other posts from Stack Overflow or by vodkhang
Published on 2010-04-22T07:20:59Z Indexed on 2010/04/22 7:23 UTC
Read the original article Hit count: 505

Filed under:

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 *)tableView:(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];
}

© Stack Overflow or respective owner

Related posts about objective-c