Reputation: 6968
I always see boilerplate for UITableViewController
declare
static NSString *CellIdentifier
in
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
Why static? I've changed this in a lot of places because my CellIdentifier
changes based on the section? whats the reasoning behind this being static? Am I affecting performance?
Upvotes: 10
Views: 3041
Reputation: 40502
cellForRowAtIndexPath:
gets called a lot. Anytime you have a method that is called over and over in a short amount of time you want to minimize the number of objects that are waiting to be auto released, because these objects will be retained on the stack until -- at minimum -- the next run loop. Using a static string ensures that the string object only gets created once, rather than each time the method is called.
It's not strictly necessary, but when you have a limited amount of memory as you do on mobile devices, you want to optimize the number of objects that are created in a short amount of time, where possible.
Upvotes: 21
Reputation: 1876
While I agree with @Answerbot regarding the performance aspect of static strings, it's also worth noting that static strings are less error prone. The IDE will autocomplete the static NSString object, thus guaranteeing that the string is named consistently.
EDIT:
If you use the following code:
static NSString *cellIndentifier = @"myCellIdentifier";
you can then freely use the variable 'cellIdentifier' without worrying about the spelling of the actual string being used.
Upvotes: 1
Reputation: 299445
When a variable is declared static
, there is only one instance of that variable in the program. Since this is a constant value that is only assigned one time, this approach avoids reserving and assigning a stack variable for it. Of course that stack variable is almost certainly optimized out by the compiler, and the string contant is already optimized into static storage by the compiler. So it's a pretty minor optimization that is as much a hint about what the developer means (i.e. all instances share the same value) as anything else.
Upvotes: 3