-1

我有两个数组,第一个包含数字,第二个使用这个数字作为索引。

NSArray *dayOfWeek = [NSArray arrayWithObjects:@"D",@"L",@"M", @"X",@"J",@"V",@"S", nil];

NSArray *arrayDays = [days componentsSeparatedByString:@" "];     

 //arrayDays  2 3 4 5 6 

     NSString *daysPrint;

     for (NSString *theDay in arrayDays) {
         NSLog(@"string %@",theDay);
         NSInteger dayIndex = (NSInteger)theDay;
         NSLog(@"integer %d", dayIndex);
         daysPrint = [NSString stringWithFormat:@"%@ %@", daysPrint, [dayOfWeek objectAtIndex:dayIndex]];

     }

在日志中:

2012-07-02 12:49:27.322 usualBike[1698:f803] string 2
2012-07-02 12:49:27.323 usualBike[1698:f803] integer 109471840

显然,当我尝试获取 dayOfWeek[109461840] 时,它会崩溃。

我该如何解决这个问题?

先感谢您

4

5 回答 5

10

daysPrint 即将为空。您需要将其设置为空白值,这是导致崩溃的原因

NSArray *dayOfWeek = [NSArray arrayWithObjects:@"D",@"L",@"M", @"X",@"J",@"V",@"S", nil];

NSArray *arrayDays = [days componentsSeparatedByString:@" "];     

//arrayDays  2 3 4 5 6 

NSString *daysPrint=@"";

for (NSString *theDay in arrayDays) {
    NSLog(@"string %@",theDay);
    NSInteger dayIndex = [theDay intValue];
    NSLog(@"integer %d", dayIndex);
    daysPrint = [NSString stringWithFormat:@"%@ %@", daysPrint, [dayOfWeek objectAtIndex:dayIndex]];

}
于 2012-07-02T10:57:44.380 回答
4

用这个

 for (NSString *theDay in arrayDays) {
    NSLog(@"string %@",theDay);
    NSInteger dayIndex = [theDay intValue];     // change this code
    NSLog(@"integer %d", dayIndex);
    daysPrint = [NSString stringWithFormat:@"%@ %@", daysPrint, [dayOfWeek objectAtIndex:dayIndex]];

}
于 2012-07-02T10:58:04.093 回答
3
for (NSString *theDay in arrayDays) {
     NSLog(@"string %@",theDay);
     int dayIndex = [theDay intValue];
     NSLog(@"integer %d", dayIndex);
     daysPrint = [NSString stringWithFormat:@"%@ %@", daysPrint, [dayOfWeek objectAtIndex:dayIndex]];

 }

这可能会帮助你...

于 2012-07-02T10:54:31.287 回答
3

您可以使用像 [theDay intValue] 这样的 NSString 实例方法进行整数转换。无需自己施展。

希望这可以帮助。

于 2012-07-02T10:55:00.560 回答
2

采用

NSInteger dayIndex = [theDay intValue]; 

反而

于 2012-07-02T10:58:03.263 回答