Hi all,
Searching and sorting is an utmost important part of any iOS app, i believe so...
Lets try to use a simpler way provided by Apple named NSPredicates that make development easier..
:) :)
We have numerous situations where NSPredicates play an important role, very few are here..
Ohhh...list may increase
:)
1) Filter an array of objects
Basic
- I have an array : arrCustomObjects
- It contains objects of type : CustomObject
- Properties of CustomObject : iD, name
- Data :
- [@"32" , @"Maria"]
- [@"51" , @"John"]
- [@"100" , @"Stuart"]
- [@"500" , @"Barbie"]
What to do
- Search object from arrCustomObjects where id = @"32"
How To do
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"iD == %@", @"32"];
NSMutableArray *filtered = (NSMutableArray*)[arrCustomObjects
filteredArrayUsingPredicate:predicate];
if(filtered.count>0)
CustomObject *customObject = [filtered objectAtIndex:0];
====================================================================
2) Filter in form of Sets
What to do
- Filter array that contains only my favorite female friends
How To do
NSArray *girlsArray = [NSArray arrayWithObjects:@"Barbie",@"Maria"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name IN %@", girlsArray];
NSMutableArray *filtered = (NSMutableArray*)[arrCustomObjects
filteredArrayUsingPredicate:predicate];
if(filtered.count>0)
CustomObject *customObject = [filtered objectAtIndex:0];
====================================================================
3) Filter using Regular Expressions
What To do
- Email ID validation using regex
How To do
NSString *emailRegex =
@"^(?i)(?:(?:https?|ftp):\\/\\/)?(?:\\S+(?::\\S*)?@)?(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?$";
NSPredicate *regextest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
if ([regextest evaluateWithObject: url] == YES)
NSLog(@"URL is valid!");
else
NSLog(@"URL is not valid!");
Enjoy the ease :) :)
No comments:
Post a Comment