Reputation: 5970
I have an iPad app that links to an SQL database to retrieve information in the following way:
NSString *strGetCodeUrl = [NSString stringWithFormat:@"%@", @"http://website/getdevicecode.php?device=" , deviceName];
NSArray *deviceArray = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strGetCodeUrl]];
This works when there is a device that matches and it retrieves the required information. However if there is not a match it returns
("")
The array however appears to have one record. Ideally I would like to stop this from happening and for the array to be empty if there is no match. Alternatively (although not very tidy) I could check the length of the entry at index 0 but I am struggling with this method.
NSString *deviceCode = [deviceArray objectAtIndex:0];
if ( [deviceCode length] == 0)
{
device does not exist
}
Any advice gratefully received.
Upvotes: 0
Views: 55
Reputation: 2013
I don't think you can tell the init method to leave out empty strings...
However, you can do this:
NSString *strGetCodeUrl = [NSString stringWithFormat:@"%@", @"http://website/getdevicecode.php?device=" , deviceName];
NSArray *deviceArray = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strGetCodeUrl]];
[deviceArray removeObject:@""];
Which also isn't as tidy as perhaps you were hoping for, but it will remove all empty strings. But at least its just 1 line of code as opposed to about 3 for the if
Per the documentation:
Removes all occurrences in the array of a given object.
Upvotes: 1
Reputation: 20410
What about this:
NSString *deviceCode = [deviceArray objectAtIndex:0];
if ([deviceCode isEqualToString:@""])
{
device does not exist
}
Upvotes: 2