Domanda

I have an array(NSArray) let's say

NSArray *cityArry = @[@"Chennai", @"Mumbai", @"Kolkata"];

For example I have mentioned the NSArray with 3 objects, but actually in runtime I have an array which contain more than 1000 objects.

Now I have the string(NSString) "chennai Tnagar"

NSString *scanedStr = @"Chennai Tnagar";

So, now I want to find out that the whether range of scanedStr contain in cityArry. For example I should get output as @"Chennai" from the cityArry.

I know we can do this by looping the NSArray and by using rangeofstring we can get the output. Since I have more than 1000 objects I don't want to do the looping. Please guide me and help me out how to solve this.

Thanks in advance

È stato utile?

Soluzione

You could basically split the string and search for the array on the cityArry.

NSString *scannedStr = @"Chennai Tnager";

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"SELF in[cd] %@", [scannedStr componentsSeparatedByString:@" "]];

[cityArray filteredArrayUsingPredicate: predicate];

Altri suggerimenti

I am certain that this is a duplicate of another answer, but I can't find it. If anybody can, please close this as a dupe.

Anyway, the IN operator works nicely on strings. Apparently it is undocumented, so you will have to decide if you want to rely on it:

NSArray *cityArray = @[@"Chennai",@"Mumbai",@"Kolkata"];

NSString *scannedStr = @"Chennai Tnagar";

NSPredicate *pred = [NSPredicate predicateWithFormat: @"SELF IN[cd] %@", scannedStr];

NSArray *result = [cityArray filteredArrayUsingPredicate: pred];

This solution has the advantage of keeping the object of the predicate on the left, which I happen to find easier to read - but as mentioned, it is not documented.

In case you wish to use a documented construct, you can swap the order of the predicate and use a normal CONTAINS:

pred = [NSPredicate predicateWithFormat: @"%@ CONTAINS[cd] SELF", scannedStr];

I propose that you make use of SQL query like by using sqlite3 as a database of the list of all cities you have. Its a bit painful implementing a database but it solves the problem I think.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top