NSRangeException 在索引处的对象中随机崩溃应用程序
NSRangeException randomly crash app in object at index
NSDictionary *latestCollection=[json objectWithString:responseString 错误:&error];
NSDictionary *data=[latestCollection valueForKey:@"results"];
if([data count]>0 && data!=nil)
{
arrayAddress=[[NSMutableArray alloc]initWithArray:[data valueForKey:@"formatted_address"]];
/*********Showing address of new location******/
[lblAddress setText:[NSString stringWithFormat:@"%@",[arrayAddress objectAtIndex:0]]];
[lblPickUpAddress setText:[NSString stringWithFormat:@"%@",[arrayAddress objectAtIndex:0]]];
}
else
{
NSLog(@"Address not available");
}
你的问题是你的 if 子句:
if([data count]>0 && data!=nil)
if
将从左到右计算,所以首先,它访问 data
以获得 count
,但它可能是 nil
,因此只需切换表达式像这样:
if( data!=nil && [data count]>0)
if
子句将停止,一旦表达式之一出现 if false
,因此它将检查 nil
,如果它不是 nil
,然后它将访问数据以获取计数。如果 data
是 nil
,那么 data
将不会被访问。这就是您的应用崩溃的原因。
NSDictionary *latestCollection=[json objectWithString:responseString 错误:&error];
NSDictionary *data=[latestCollection valueForKey:@"results"];
if([data count]>0 && data!=nil)
{
arrayAddress=[[NSMutableArray alloc]initWithArray:[data valueForKey:@"formatted_address"]];
/*********Showing address of new location******/
[lblAddress setText:[NSString stringWithFormat:@"%@",[arrayAddress objectAtIndex:0]]];
[lblPickUpAddress setText:[NSString stringWithFormat:@"%@",[arrayAddress objectAtIndex:0]]];
}
else
{
NSLog(@"Address not available");
}
你的问题是你的 if 子句:
if([data count]>0 && data!=nil)
if
将从左到右计算,所以首先,它访问 data
以获得 count
,但它可能是 nil
,因此只需切换表达式像这样:
if( data!=nil && [data count]>0)
if
子句将停止,一旦表达式之一出现 if false
,因此它将检查 nil
,如果它不是 nil
,然后它将访问数据以获取计数。如果 data
是 nil
,那么 data
将不会被访问。这就是您的应用崩溃的原因。