简体   繁体   中英

Objective-C Expected Identifier - simple syntax debugging problem

I need help debugging this error Expected Identifier . The code is -

+(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;
}

I get the error marker at -1] , underneath the ] .

I think this line:

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

should look like this:

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

I changed initWithFormat due to a compiler warning. You are not subsituting anything so initWithString should suffice for the beginning.

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

EDIT: Just like Nick Weaver pointed out you should probably use initWithString: :

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

EDIT 2: Not sure why you need to create a new string. Isn't the following sufficient?

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

Note: I think the real issue here is that you don't really know what brackets are used for.

Instead of

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

Use

NSString *dayName = [daysOfTheWeek objectAtIndex:[components weekday]-1];
+(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;
}

will work:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM