cellForRowAtIndexPath method question

Discussion in 'iOS Programming' started by daproject85, Sep 10, 2012.

  1. daproject85 macrumors member

    Apr 13, 2011
    Hi Forum,

    can someone please explain to me that if i have this code

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
        static NSString *CellIdentifier = @"Top Places Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil)
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    so let me see if i even know what the heck i am talking about. so the "dequeueReusableCellWithIdentifier" method is purely for performance.
    basically we are saying if the cell exists and its off screen just re-use it when I need to draw another one. So if we dont have any off screen.. lets say my table only has 5 rows which all 5 fit on the screen. At that point there is nothing to "dequeue" so i need to create new cells. Hence the IF statement Makes sense. But i ran the exact same code with the if statement commented out, AND IT STILL RUNS!..... i am so confused Please shed some light on this.
  2. 1458279 Suspended


    May 1, 2010
    I'll take a stab at this:
    The program will work the same with or without cell reuse. Cell reuse is a way to conserve memory. If you have a small number of rows and don't scroll a lot, it won't really matter much.

    If you have a large number or rows and don't reuse cells, you are using memory that the program might need.

    The program will function the same.

    As a "rule of thumb" it's best to have the cell reuse because you might end up loading more rows than you once though.

    Let me know if this helps or not.
  3. Scott90 macrumors 6502

    Jul 14, 2008
    Creating a cell using alloc/init is not necessary anymore with storyboards, as you'll have a prototype cell with that reuse identifier. This means that a call to dequeueReusableCellWithIdentifier always returns a cell (provided that the identifier is correct), and the if statement is never executed anyway.

    darealjakesh is correct. A table view will only put a few cells in memory, just enough to be able to show a full screen of cells. Once scrolled off-screen, a cell stays in memory, but will go to the reuse stack. It can now be reused and shown at the bottom of the visible portion of the table.
  4. MattInOz macrumors 68030


    Jan 19, 2006
    -dequeueReusableCellWithIdentifier has been upgraded over the last few versions to use a a bunch of optimizations. As scott said if your using a storyboard you can set the Reuse ID there. If your using a NIB or a custom UITableView Class you can register them against a reuse ID and avoid a bunch of spaghetti code in your cellForRowAtIndexpath method.

Share This Page