我无法使用文字整数访问 NSArray 数据,它会抛出一些异常,索引 bouds (0 , 0) 但实际上这是错误的,因为如果我动态循环它它就可以工作......我的代码:
for (NSString *cada in barcos)
{
NSArray *datos = [cada componentsSeparatedByString:@";"];
NSString *consulta = [NSString stringWithFormat:@"INSERT OR REPLACE INTO Barco (ID,Zona,Nombre,Matricula,Imagen) VALUES ('%d','%@',\"%@\",\"\",\"%@\");",contador,[datos objectAtIndex:0],[datos objectAtIndex:1],[datos objectAtIndex:2]];
insert_stmt = (char *)[consulta UTF8String];
sqlite3_prepare_v2(db, insert_stmt, -1, &statement, NULL);
sqlite3_finalize(statement);
contador++;
}
我测试了这个并且有效......但我不想要这样:
for (NSString *cada in barcos)
{
NSArray *datos = [cada componentsSeparatedByString:@";"];
for (int c = 0; c < [datos count]; c++)
NSLog(@"%@",[datos objectAtIndex:c]);
// It prints all very good, there is only 0 to 2 position always
}
编辑:
for (NSString *cada in barcos)
{
NSArray *datos = [cada componentsSeparatedByString:@";"];
for (int c = 0; c < [datos count]; c++)
{
NSLog(@"posicion array %d - dato: %@",c,[datos objectAtIndex:c]);
}// Here we are good, the loop is OK
NSString *consulta = [NSString stringWithFormat:@"INSERT OR REPLACE INTO Barco (ID,Zona,Nombre,Matricula,Imagen) VALUES ('%d','%@',\"%@\",\"\",\"%@\");",contador,[datos objectAtIndex:0],[datos objectAtIndex:1],[datos objectAtIndex:2]]; // Here crash, cannot go to objectAtIndex:1
/*insert_stmt = (char *)[consulta UTF8String];
sqlite3_prepare_v2(db, insert_stmt, -1, &statement, NULL);
sqlite3_finalize(statement);*/
contador++;
}
我的数组打印这个:
2013-01-22 12:54:36.386 whales[4076:707] posicion array 0 - dato: Spirit of the seas
2013-01-22 12:54:36.403 whales[4076:707] posicion array 1 - dato: spirit_of_the_seas.bmp
2013-01-22 12:54:36.410 whales[4076:707] posicion array 2 - dato: 1
2013-01-22 12:54:36.419 whales[4076:707] posicion array 0 - dato: Nashira I
2013-01-22 12:54:36.425 whales[4076:707] posicion array 1 - dato: nashira1.bmp
2013-01-22 12:54:36.432 whales[4076:707] posicion array 2 - dato: 2
2013-01-22 12:54:36.441 whales[4076:707] posicion array 0 - dato: Tina Excursiones
2013-01-22 12:54:36.448 whales[4076:707] posicion array 1 - dato: tinaexcursiones.bmp
2013-01-22 12:54:36.454 whales[4076:707] posicion array 2 - dato: 3
2013-01-22 12:54:36.461 whales[4076:707] posicion array 0 - dato: Catlanza
2013-01-22 12:54:36.467 whales[4076:707] posicion array 1 - dato: catlanza.bmp
2013-01-22 12:54:36.473 whales[4076:707] posicion array 2 - dato: 3
2013-01-22 12:54:36.478 whales[4076:707] posicion array 0 - dato:
这是我的 for + NSLog 所以没问题,但手动不行
最佳答案
使用 if 保护对数组的访问:
if( datos.count>=3)
{
NSString *consulta = [NSString stringWithFormat:@"INSERT OR REPLACE INTO Barco (ID,Zona,Nombre,Matricula,Imagen) VALUES ('%d','%@',\"%@\",\"\",\"%@\");",contador,[datos objectAtIndex:0],[datos objectAtIndex:1],[datos objectAtIndex:2]];
}
else
{
NSLog(@"datos count is %u",datos.count);
}
这将使您了解 datos 数组何时没有 3 个元素。
关于ios - 无法使用文字整数访问我的 NSArray 但可以动态工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14458434/