询问似乎具有空条目的NSArray

时间:2013-11-29 09:16:02

标签: ios objective-c

我有一个iPad应用程序链接到SQL数据库,以便通过以下方式检索信息:

NSString *strGetCodeUrl = [NSString stringWithFormat:@"%@", @"http://website/getdevicecode.php?device=" , deviceName];
NSArray *deviceArray = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strGetCodeUrl]];

当设备匹配并检索所需信息时,此方法有效。但是如果没有匹配则返回

( “”)

然而,阵列似乎有一条记录。理想情况下,我想阻止这种情况发生,如果没有匹配则数组为空。或者(虽然不是很整洁)我可以检查索引0处条目的长度,但我正在努力使用这种方法。

NSString *deviceCode = [deviceArray objectAtIndex:0];
if ( [deviceCode length] == 0)
{
device does not exist
}

感谢任何建议。

2 个答案:

答案 0 :(得分:2)

这个怎么样:

NSString *deviceCode = [deviceArray objectAtIndex:0];
if ([deviceCode isEqualToString:@""])
{
device does not exist
}

答案 1 :(得分:1)

我认为你不能告诉init方法遗漏空字符串......

但是,你可以这样做:

NSString *strGetCodeUrl = [NSString stringWithFormat:@"%@", @"http://website/getdevicecode.php?device=" , deviceName];
NSArray *deviceArray = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strGetCodeUrl]];
[deviceArray removeObject:@""];

这也不像你希望的那样整洁,但它会删除所有空字符串。但至少只有1行代码而不是3代表if

根据documentation

  

删除给定对象数组中的所有匹配项。