NSString: why use static over a literal?

Master-Detail Xcode project template generates code, for example:

// 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; } 
  • Why declare NSString as static ? Why not just use a string literal as shown 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; } 
  • When should I use static over literals with NSString , NSObject , scalors ( NSInteger , CGFloat , etc.), etc.?

  • Is it more efficient to use the NSInteger literal instead of defining a static variable that points to it and uses this?

+4
source share
1 answer

Staticity allows you to define only one instance of the NSString object that will be used. If you used a string literal instead, there is no guarantee that only one object will be created; instead, the compiler can assign a new line each time the loop is called, and then pass this to the dequeue method, which will use string comparisons to check if any cell is available.

In practice, there is no difference; both static and literals will work fine. But with static, you tell Obj-C that it should use the same instance every time. Although this is unlikely to cause any problems for you, it is recommended that you use static if you plan to always use the same object.

+8
source

Source: https://habr.com/ru/post/1382332/


All Articles