NSString:为什么使用static over literal?

ma1*_*w28 4 static objective-c string-literals nsstring

Master-Detail Xcode项目模板生成如下代码:

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}
Run Code Online (Sandbox Code Playgroud)
  1. 为什么要声明NSString为static?为什么不直接使用字符串文字,如下所示?

    // Customize the appearance of table view cells.
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    
        [self configureCell:cell atIndexPath:indexPath];
        return cell;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 什么时候应该使用静态过与文字NSString,NSObject,scalors( ,NSInteger,CGFloat等),等等?

  3. 使用文字NSInteger而不是定义指向它并使用它的静态变量是否更高效?

Edu*_*coz 8

static允许您仅定义要使用的NSString对象的一个​​实例.如果您使用了字符串文字,则无法保证只创建一个对象; 编译器可能会在每次调用循环时最终分配一个新字符串,然后将其传递给dequeue方法,该方法将使用字符串比较来检查是否有任何单元格可用.

在实践中,没有区别; static或literal都可以正常工作.但是对于静态,你告诉Obj-C每次都应该使用相同的实例.虽然对于这种情况,这不太可能导致任何问题,但如果您打算始终使用相同的对象,则使用静态是一种好习惯.

  • 我同意.只需添加一点.使用静态变量而不是文字只会使代码更容易维护,因为您只在一个地方更改字符串./关于NSInteger和CGFloat,它们不是对象,所以它有点不同. (3认同)
  • 从代码易读性的角度来看,你说的是真的,但是应该注意到ObjC中的文字字符串是在编译时创建的并存储在二进制文件的DATA段中.文字字符串既是不朽的又是重用的. (2认同)