Objective-C期望标识符 - 简单的语法调试问题

时间:2011-05-05 09:07:01

标签: iphone objective-c ios4

我需要帮助调试此错误Expected Identifier。代码是 -

+(NSString *)dayOfWeek {
    NSDate *day = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSWeekdayCalendarUnit fromDate:day];
    day = [calendar dateFromComponents:components];
    NSLog(@"The DAY OF THE WEEK is -- %@", day);
    NSArray *daysOfTheWeek = [NSArray arrayWithObjects:@"Sunday", @"Monday", @"Tuesday", @"Wednesday", @"Thursday", @"Friday", @"Saturday", nil];

    NSString *dayName = [[[NSString alloc] initWithFormat:[daysOfTheWeek objectAtIndex:[[components weekday]-1]]]];
    return dayName;
}

我在-1]下面的]处获得错误标记。

4 个答案:

答案 0 :(得分:5)

我认为这一行:

NSString *dayName = [[[NSString alloc] initWithFormat:[daysOfTheWeek objectAtIndex:[[components weekday]-1]]]];

应如下所示:

NSString *dayName = [[NSString alloc] initWithString:[daysOfTheWeek objectAtIndex:[components weekday]-1]];

由于编译器警告,我更改了initWithFormat。你没有贬低任何东西,所以initWithString应该足够开头。

答案 1 :(得分:1)

NSString *dayName = [[NSString alloc] initWithFormat:[daysOfTheWeek objectAtIndex:[components weekday]-1]];

编辑:就像Nick Weaver指出你应该使用initWithString:

NSString *dayName = [[NSString alloc] initWithString:[daysOfTheWeek objectAtIndex:[components weekday]-1]];

编辑2:不确定为什么需要创建新字符串。以下是否足够?

NSString *dayName = [daysOfTheWeek objectAtIndex:[components weekday]-1];

注意:我认为这里的真正问题是您并不真正知道使用了哪些括号。

答案 2 :(得分:1)

而不是

NSString *dayName = [[[NSString alloc] initWithFormat:[daysOfTheWeek objectAtIndex:[[components weekday]-1]]]];

使用

NSString *dayName = [daysOfTheWeek objectAtIndex:[components weekday]-1];

答案 3 :(得分:0)

+(NSString *)dayOfWeek {
    NSDate *day = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSWeekdayCalendarUnit fromDate:day];
    day = [calendar dateFromComponents:components];
    NSLog(@"The DAY OF THE WEEK is -- %@", day);
    NSArray *daysOfTheWeek = [NSArray arrayWithObjects:@"Sunday", @"Monday", @"Tuesday", @"Wednesday", @"Thursday", @"Friday", @"Saturday", nil];
    NSString *dayName = [[NSString alloc] initWithFormat:[daysOfTheWeek objectAtIndex:[components weekday] - 1 ]];
    return dayName;
}

将起作用:)