What’s the difference?


It”s late and I’m stumped. Trying to figure out what’s the difference between

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
	UITableViewCell *cell = [tableView
							 dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc]
				 initWithFrame:CGRectZero
				 reuseIdentifier:CellIdentifier] autorelease];
	}
	cell.text = [teams objectAtIndex:indexPath.row];
	return cell;
}

and:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	UITableViewCell *cell = [tableView
							 dequeueReusableCellWithIdentifier:@"Cell"];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc]
				 initWithFrame:CGRectZero
				 reuseIdentifier:@"Cell"] autorelease];
	}
	cell.text = [teams objectAtIndex:indexPath.row];
	return cell;
}

I’ve seen this pattern twice, once in an iPhone SDK book and once in code generated by XCode. That’s enough to make me feel like there’s a reason we use a temp variable here. (Incidentally I didn’t notice the redundancy in my refactoring until I pasted/posted the code snippet. If the motivation is merely to cut down redundancy then I’m fine with that, I just wanna make sure I’m not missing something important.)

2 thoughts on “What’s the difference?

  1. You’re putting an autoreleased NSString at the other end of a static pointer, when in fact every time this method is called, a new NSString is going to get allocated, on the heap, wherever malloc() damn well pleases, and thus that pointer isn’t really going to be static. Try taking out “static”. If you’re concerned about performance, use a #define to declare the column identifer, or declare the static NSString in the header, outside of the @implementation scope, where you can be certain the allocation will only happen once.

  2. That makes sense. And it clears my other question before I had to ask. I was wondering how/why someone would declare a static inside a method and how it worked. My background in C makes me familiar but coming mostly from Java that seemed really odd and more like an edge case thing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s