Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the advantage of using a static NSString for CellIdentifier?

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?

like image 741
j_mcnally Avatar asked Mar 12 '13 20:03

j_mcnally


2 Answers

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.

like image 136
JiuJitsuCoder Avatar answered Nov 14 '22 19:11

JiuJitsuCoder


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.

like image 25
memmons Avatar answered Nov 14 '22 20:11

memmons