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];
NSCalenda开发者_开发百科r *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.
Instead of
NSString *dayName = [[[NSString alloc] initWithFormat:[daysOfTheWeek objectAtIndex:[[components weekday]-1]]]];
Use
NSString *dayName = [daysOfTheWeek objectAtIndex:[components weekday]-1];
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.
+(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 :)
精彩评论