在Objective-c或iPhone编程中,"MyIdentifier"是什么意思

Pic*_*ght 0 iphone cocoa-touch objective-c uitableview

我对以下行"静态NSString*MyIdentifier = @"MyIdentifier";"感到困惑 在方法中:cellForRowAtIndexPath

那条线做什么?它只是创建一个指向NSString对象的随机指针并为其分配字符串吗?为什么它被称为MyIdentifier,我在很多例子中都看到了这一点.

#import "AddToFavorites.h"


@implementation AddToFavorites

- (id)initWithStyle:(UITableViewStyle)style {
  if (self = [super initWithStyle:style]) {
  }
  return self;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return 1;
}


- (NSInteger)tableView:(UITableView *)tableView 
numberOfRowsInSection:(NSInteger)section {
  return 5;
}


- (UITableViewCell *)tableView:(UITableView *)tableView 
cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *MyIdentifier = @"MyIdentifier";

UITableViewCell *cell = [tableView 
dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero 
reuseIdentifier:MyIdentifier] autorelease];
}
// Configure the cell

return cell;
}

@end
Run Code Online (Sandbox Code Playgroud)

这是另一个例子,这个有一个不同的字符串CellIdentifier.

- (UITableViewCell *)tableView:(UITableView *)tableView 
cellForRowAtIndexPath:(NSIndexPath *)indexPath  {

static NSString *CellIdentifier = @"TimeZoneCell";

UITableViewCell *cell = [tableView 
dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [self tableviewCellWithReuseIdentifier:CellIdentifier];
}

[self configureCell:cell forIndexPath:indexPath];
return cell;
}
Run Code Online (Sandbox Code Playgroud)

Nil*_*ect 6

UITableViews可以自动重复使用单元格来节省内存.要利用这一点,您必须指定一个"重用标识符",UITableView使用它来查找现有单元格("dequeueReusbaleCellWithIithntifier"),其标识与您创建的单元格相同,如果它找不到现有细胞.

该行创建一个静态变量(全局,因为它由所有代码路径共享,只初始化一次,但本地只能在此方法中访问它)以保存标识符的NSString.我的猜测是,这是为了确保每次使用相同的指针,因为比较指针既快速又容易,而比较字符串的内容可能需要更长的时间.