代码之家  ›  专栏  ›  技术社区  ›  AlcubierreDrive

只有在使用中间变量时才有效

  •  1
  • AlcubierreDrive  · 技术社区  · 15 年前

    我试图将uilabel的文本设置为与nsdateComponents中表示的星期几的名称相同。我使用以下代码:

    NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease];
    dateComponents.weekday = 1; //Sunday
    NSString * const weekdayNames[8] = {@"Array starts at 1", @"Sunday", @"Monday", @"Tuesday", @"Wednesday", @"Thursday", @"Friday", @"Saturday"};
    
    UILabel *myLabel = [[[UILabel alloc] init] autorelease];
    myLabel.text = weekdayNames[dateComponents.weekday]; //compiler error: Assignment of read-only variable 'prop.49'
    

    我可以通过以下三种方式之一使代码工作:

    1. 使weekdaynames不是常量
    2. 将dateComponents.weekday分配给中间int变量,然后将其用作数组索引
    3. 在调用settext之前,将weekday[dateComponents.weekday]分配给中间nsstring*变量:

    但我想知道我最初编写的代码为什么会失败。

    1 回复  |  直到 15 年前
        1
  •  0
  •   diciu    15 年前

    您没有正确初始化nsdateComponents,因此 平日 不返回您期望的值。见 the documentation .

    现在,您可以使用当前日期初始化它:

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
    int weekday = [weekdayComponents weekday];
    

    后期编辑:初始化 部分问题,要修复编译器错误更改:

    NSString * const weekdayNames[8] =
    

    NSString const * weekdayNames[8] =
    

    (指向常量nsstring的指针)。

    但是,当你这样做的时候,你会发出警告 “传递”settext:“的参数1:放弃指针目标类型中的限定符” 因为您要将常量指针传递给需要指针的函数。要修复警告,可以将参数强制转换为settext to(nsstring*)。

    完全删除const限定符可能是有意义的。 nsstring在objective-c中已经是不可变的,所以它们已经是常量了。