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;
}
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;
}
When should I use static over literals with NSString
, NSObject
, scalors (NSInteger
, CGFloat
, etc.), etc.?
Is it more performant to use a literal NSInteger
rather than defining a static variable that points to it and using that?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With