Search code examples
iosobjective-cuitableviewnsarray

Why adding (by typing in code) an object to NSArray freezes my app?


I am in dead end. I have UITableViewCell class that is used as "Settings" tab in my application. The cells are created and counted like this:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.refreshControl = nil;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.scrollEnabled = NO;

(...) Note that Title 4 is commented

NSArray* titles = @[ @"Title1", @"Title2", @"Title3"/*,@"Title4"*/];

    for (int i = 0; i < titles.count; i++)
    {
        SettingsTableCell* cell = [[SettingsTableCell alloc] initWithFrame: CGRectMake(0, 0, self.tableView.frame.size.width, self.tableView.frame.size.height / titles.count)];
        cell.textLabel.text = [titles objectAtIndex:i];
        cell.textLabel.numberOfLines = -1;
        cell.backgroundColor = i % 2 == 0 ? [Colors colorForType:kLegiaColorWhite] : [UIColor whiteColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = [Fonts fontWithSize: IPHONE_IPAD(18.0, 24.0)];
        cell.accessoryView = i == 0 ? calendarSwitch : (i == 1 ? scheduleFilterSwitch : wifiSwitch);

        [cells addObject:cell];
    }
}

I think down below everything is correct

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [cells count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.tableView.frame.size.height / [self tableView:tableView numberOfRowsInSection:indexPath.section];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [cells objectAtIndex:indexPath.row];
}

Please note that the problem occurs when I uncomment fourth title in my array. When I enter into Settings tab it's starting to loop itself (I checked in debugger) and app rather freezes than crashes. With three titles it works like a charm. Could You help me finding why?

EDIT:

After @Avi suggested, I put breakpoint on heightForRowAtIndexPath and it loops on this specific method. In debugger I have this: StackView


Solution

  • After researching and reducing items in *titles array (it worked for 1 and 2 items), I noticed that every cell had it own UISwitch, and 4th one doesn't have, as it is not needed. And layout subviews couldn't complete because of this error. So I changed the following line:

       cell.accessoryView = i == 0 ? calendarSwitch : (i == 1 ? scheduleFilterSwitch : wifiSwitch);
    

    to that one

    cell.accessoryView = i == 0 ? calendarSwitch : (i == 1 ? scheduleFilterSwitch : i == 2 ? wifiSwitch : nil);
    

    I worked! Help You guys for help!