2012-07-02 81 views
-1

我有兩個數組,第一個內容數字和第二個使用這個數字作爲索引。nsstring和nsinteger轉換

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]崩潰。

我該如何解決這個問題?

預先感謝您

+0

的NSArray * arrayDays = [天componentsSeparatedByString的原因: @「」]在這個「days」是一個字符串?使用NSLog打印「days」。獲取「dayIndex」,使用[theDay intValue]。 – Madhumitha

+0

字符串daysPrint出現爲null,而dayOfWeek也沒有用於索引dayIndex的元素。 –

+0

如何獲取「天」字符串。請添加一些代碼。 – Madhumitha

回答

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]]; 

} 
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

您可以像使用[theDay的intValue] NSString的實例方法整數轉換。不需要投你自己。

希望這會有所幫助。

10

daysPrint正在爲null。 ü需要assing空白值,這是崩潰

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

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

//arrayDays 2 3 4 5 6 

NSString *[email protected]""; 

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

} 
2

使用

NSInteger dayIndex = [theDay intValue]; 

代替

相關問題