Objective c 数组索引越界
当我运行下面的代码时,我得到Objective c 数组索引越界,objective-c,arrays,Objective C,Arrays,当我运行下面的代码时,我得到 Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFArray objectAtIndex:] 我知道在循环的某个点上,数组的索引不存在。 如何处理 int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFArray objectAtIndex:]
我知道在循环的某个点上,数组的索引不存在。
如何处理
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSArray *t = [NSTimeZone knownTimeZoneNames];
for(id x in t)
{
NSArray *tmpArray = [x componentsSeparatedByString:@"/"];
NSLog(@"%@", [tmpArray objectAtIndex:1]);
}
[pool drain];
return 0;
}
并非所有时区名称都包含斜杠。例如,
UTC
时区名称不包含斜杠。因此tmpArray
可能只包含一个索引为0的字符串
也许这会满足您的需求:
NSLog(@"%@", [tmpArray lastObject]);
并非所有时区名称都包含斜杠。例如,
UTC
时区名称不包含斜杠。因此tmpArray
可能只包含一个索引为0的字符串
也许这会满足您的需求:
NSLog(@"%@", [tmpArray lastObject]);
您可能需要在访问索引1之前检查tmpArray的大小您可能需要在访问索引1之前检查tmpArray的大小您应该首先检查
tmpArray的大小
:
NSArray *tmpArray = [x componentsSeparatedByString:@"/"];
if ([tmpArray count] > 1)
NSLog(@"%@", [tmpArray objectAtIndex:1]);
您应该首先检查
tmpArray
的大小:
NSArray *tmpArray = [x componentsSeparatedByString:@"/"];
if ([tmpArray count] > 1)
NSLog(@"%@", [tmpArray objectAtIndex:1]);
索引从0开始,索引1可能没有任何内容。索引从0开始,索引1可能没有任何内容。