Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString: Why use static over literal?

The Master-Detail Xcode Project Template generates code like:

// 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];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}
  1. Why declare the NSString as static? Why not just use the string literal, like below?

    // Customize the appearance of table view cells.
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    
        [self configureCell:cell atIndexPath:indexPath];
        return cell;
    }
    
  2. When should I use static over literals with NSString, NSObject, scalors (NSInteger, CGFloat, etc.), etc.?

  3. Is it more performant to use a literal NSInteger rather than defining a static variable that points to it and using that?

like image 286
ma11hew28 Avatar asked Feb 22 '23 08:02

ma11hew28


1 Answers

The static allows you to define only one instance of the NSString object to be used. If you used the string literal instead, there's no guarantee that only one object will be created; the compiler may instead end up allocating a new string every time the loop is called, and then passing that to the dequeue method, which will use string comparison to check if any cell is available.

In practice, there's no difference; both static or literal will work fine. But with the static you're telling Obj-C that it should use the same instance every time. Although for this case this would very unlikely cause any problems for you, it's good practice to use static if you plan to always use the same object.

like image 104
Eduardo Scoz Avatar answered Feb 28 '23 06:02

Eduardo Scoz