aaronium112
aaronium112

Reputation: 3088

Why is the static keyword used in UITableViewCell identifiers?

I've read up on "static" on several occasions, including just before posting this question. I'm still searching for an "Aha" though.

In the context of UITableView's static comes up in Cell Identifiers in every piece of code I've looked at. For example in a recent CellForRowAtIndexPath:

    static NSString *defaultIndentifier = @"Managed Object Cell Identifier";

My question is why do we need and use "static"?

Upvotes: 22

Views: 3469

Answers (3)

joeybladb
joeybladb

Reputation: 247

My guess is that by declaring the string as static, that every time it gets passed into -dequeueReusableCellWithIdentifier:CellIdentifierforIndexPath: that the same pointer is used each time (as statically declared variables are allocated only once on the heap, very early in a program's execution)

[NSString -isEqualToString:] is most likely implemented to perform a pointer compare first, followed by a character-wise compare as the fallback, which I supposed could shave off a few cycles on each iteration.

There's not much to gain from this, as (a) table cell re-population operates on a typically very small set of cells, and is well optimized, and (b) table refresh is bursty -- it happens once and then doesn't happen again until the user scrolls or application logic changes up the content -- if you end up calling -reloadTable 100 times a second, then there's clearly something wrong with your application logic.

I suspect the static keyword is a vestigial legacy convention -- maybe back in the day, Apple hashed on the pointer, rather than performing a proper string compare.

Upvotes: 0

Lily Ballard
Lily Ballard

Reputation: 185721

There's no real benefit here. It's mostly just a hint to the reader that the same value is used for all cells in this particular bit of code. As the identifier itself is a constant string, it gets compiled into an immutable chunk of memory and referenced as the same pointer every time, e.g. there is no cost involved in constructing the string even if you remove the static keyword.

Upvotes: 20

Lou Franco
Lou Franco

Reputation: 89222

So that it will only be constructed once. If it's not static, you'll be making one every time the message is sent (which is a lot)

Upvotes: 14

Related Questions