nsstring和nsinteger转换

时间:2012-07-02 10:50:54

标签: iphone objective-c

我有两个数组,第一个是内容编号,第二个使用这个数字作为索引。

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]它崩溃时。

我该如何解决这个问题?

提前谢谢

5 个答案:

答案 0 :(得分: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]];

}

答案 1 :(得分: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]];

}

答案 2 :(得分:3)

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

 }

这可能会对你有帮助......

答案 3 :(得分:3)

您可以使用[theDay intValue]等NSString实例方法进行整数转换。不需要投你自己。

希望这有帮助。

答案 4 :(得分:2)

USE

NSInteger dayIndex = [theDay intValue]; 

代替