我有以下代码块:
NSNumber* dayNsNumber = [[NSNumber alloc] initWithInt:dayNumber+1];
NSLog(@"dayNsNumber: %d", [dayNsNumber intValue]);
if(boolVar){
UIAlertView* success = [[UIAlertView alloc] initWithTitle:@"Title" message:[NSString stringWithFormat:@"Day %d!", dayNumber+1] delegate:self cancelButtonTitle:nil otherButtonTitles:@"Star", nil];
[success show];
NSLog(@"dayNsNumber: %d", [dayNsNumber intValue]);
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
dayNsNumber, "Day Number",
[self getCurrentLocalDate], @"Date",
[self getCurrentLocalTime], @"Time",
nil];
}
当我运行代码时,它会在params
NSDictionary
初始化时挂起,并说dayNsNumber
为nil
。
Xcode显示线程1:EXC_BAD_ACCESS(代码= 1)。
如何解决这个问题?我想将dayNsNumber
添加到我的params
字典中。
此外,还有getCurrentLocalDate
和getCurrentLocalTime
:
-(NSString*)getCurrentLocalDate;{
NSString *formatString = [NSDateFormatter dateFormatFromTemplate:@"dd-MM-yyyy" options:0 locale:[NSLocale currentLocale]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:formatString];
NSString *todayString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"todayString: \"%@\"", todayString);
return todayString;
}
-(NSString*)getCurrentLocalTime;{
NSString *formatString = [NSDateFormatter dateFormatFromTemplate:@"HH:mm:ss zzz" options:0 locale:[NSLocale currentLocale]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:formatString];
NSString *timeString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"timeString: \"%@\"", timeString);
return timeString;
}
答案 0 :(得分:5)
问题在于密钥:"Day Number"
应为@"Day Number"
。
另请注意,您现在可以为数字,数组和词典使用新语法。例如,这个
NSNumber* dayNsNumber = [[NSNumber alloc] initWithInt:dayNumber+1];
可以像这样重写:
NSNumber* dayNsNumber = @(dayNumber+1);
和字典初始化可以像这样完成:
NSDictionary *params = @{
@"Day Number" : dayNsNumber
, @"Date" : [self getCurrentLocalDate]
, @"Time" : [self getCurrentLocalTime]
};
答案 1 :(得分:1)
试试这个
NSDictionary *params = [[NSDictionary alloc]init];
[params setValue:[daysNumber stringValue] forKey:@"Day Number"];