NSPredicate - Evaluate with two conditions - iphone

I want to know how to evaluate NSString which satisfied two conditions using NSPredicate. For example how to check a string that should have atleast one upper case letter and atleast one number.

You can use ANDing for two or more condition.
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entityDescription];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"fbUID = %# AND birthDate = %d AND birthMonth = %d AND greetingYear = %d", uID, birthDate, birthMonth, greetingYear];
//NSLog(#"%# :",predicate);
[fetchRequest setPredicate:predicate];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
You can check more on NSPredicate HERE.

One way to do this is:
NSCharacterSet *upperCaseCharacters = [NSCharacterSet characterSetWithCharactersInString:#"ABCDEFGHIJKLKMNOPQRSTUVWXYZ"];
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
return ([evaluatedObject rangeOfCharacterFromSet:upperCaseCharacters].location != NSNotFound && [evaluatedObject rangeOfCharacterFromSet:numbers].location != NSNotFound);
}];
NSString *stringToEvaluate = #"aasad5D";
BOOL result = [predicate evaluateWithObject:stringToEvaluate];
Another solution is compound predicate, see this question for example how to use compound predicates create a Compound Predicate in coreData xcode iphone.

I found a solution for this by myself. I used regular expression with predicate to solve this issue.
NSPredicate *pwdCheck = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", #"(?=.*?[A-Z])(?=.*?[0-9]).*"];
bool isValid = [pwdCheck evaluateWithObject:#"99a99A3w"];
Thanks for your help

Related

Memory leak when returning an NSManagedObject from a function with Xcode (ARC)

I've a function which returns a NSManagedObject based on a predicate which seems to be memory leaking badly.
- (WordMap *)getWordMapForLetter:(NSString *)letter
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"WordMap" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
WordMap *wordMap = Nil;
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"letter == %#", letter];
[fetchRequest setPredicate:predicate];
NSError *error;
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if ([fetchedObjects count] > 0) {
wordMap = (WordMap *)[fetchedObjects objectAtIndex:0];
}
return wordMap;
}
The problem looks to lie specifically with the following line as commenting it out stops the leak...
wordMap = (WordMap *)[fetchedObjects objectAtIndex:0];
I'm presuming the problem is that I'm returning a reference to an array item that was created within the scope of the function so therefore ARC cannot dispose of the array afterwards?
Is that correct or is the problem something else entirely? Regardless, I'm not at all sure how to go about stopping the leak- suggestions?

Database update using Core Data

I am trying to update my local database when app gets response from the web server. When app gets the update from web server, I fetch the data from the local database by matching the id with the response and get one row and perform update code but local database does not get updated and also does not give an error.
What should be the solution???
-(void)checkID:(NSMutableDictionary *)dict
{
NSDictionary *dictEvent = [dict objectForKey:#"Event"];
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *selectedManagedObject = nil;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Events" inManagedObjectContext:context];
NSSortDescriptor *sortDescObj = [[NSSortDescriptor alloc] initWithKey:#"event_id" ascending:YES];
NSError *error = nil;
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"user_id=%# and event_id=%#",[NSNumber numberWithInt:[[dictEvent valueForKey:#"user_id"] intValue]],[NSNumber numberWithInt:[[dictEvent valueForKey:#"id"] intValue]]]];
NSLog(#"Predicate = %#",predicate);
NSArray *arrSortDescriptors = [NSArray arrayWithObject:sortDescObj];
[fetchRequest setSortDescriptors:arrSortDescriptors];
[fetchRequest setEntity:entity];
[fetchRequest setReturnsDistinctResults:YES];
[fetchRequest setPredicate:predicate];
NSArray *arrResult = [context executeFetchRequest:fetchRequest error:&error];
if ([arrResult count]>0)
{
NSArray *arrKey = [dictEvent allKeys];
NSArray *arrValue = [dictEvent allValues];
NSLog(#"ArrKey : %#\nArrValue : %#",arrKey,arrValue);
selectedManagedObject = [arrResult objectAtIndex:0];
for(int i = 0; i < [arrKey count] ; i++)
{
NSLog(#"selectedMng :- %#",selectedManagedObject);
NSLog(#"KEY: %#\t: %#",[arrKey objectAtIndex:i],[arrValue objectAtIndex:i]);
if ([[arrKey objectAtIndex:i]isEqualToString:#"id"])
{
[selectedManagedObject setValue:[arrValue objectAtIndex:i] forKey:#"event_id"];
}
else if([[arrKey objectAtIndex:i]isEqualToString:#"invited_status"])
{
[selectedManagedObject setValue:[arrValue objectAtIndex:i] forKey:#"invite_status"];
}
else
{
[selectedManagedObject setValue:[arrValue objectAtIndex:i] forKey:[arrKey objectAtIndex:i]];
}
}
if (! [selectedManagedObject.managedObjectContext save:&error])
{
NSLog(#"updateEntityIntoDataBaseNamed - Error :: %#", [error localizedDescription]);
}
// }
}
}
Besides modifying your predicate as suggested by #Martin
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"user_id=%# && event_id=%#",
[NSNumber numberWithInt:[[dictEvent valueForKey:#"user_id"] intValue]],
[NSNumber numberWithInt:[[dictEvent valueForKey:#"id"] intValue]]
];
note that in two cases, you are updating your object using non matching keys: this happens for id and event_id, and for invited_status and invite_status.
You cannot use stringWithFormat within predicateWithFormat. Your predicate should probably look like this:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"user_id=%# and event_id=%#",
[NSNumber numberWithInt:[[dictEvent valueForKey:#"user_id"] intValue]],
[NSNumber numberWithInt:[[dictEvent valueForKey:#"id"] intValue]]
];

fast research with nspredicate

In my application i have a large table of around 20.000 items. I am displaying it on tableview. But the search bar is too slow while doing dynamic search. I have read that NSPredicate method is high performance then NSRange.
I don't know how applicate this method.
My code is :
- (void)filterContentForSearchText:(NSString*)searchText
{
[self.filteredListContent removeAllObjects];
for (Book *book in listContent)
{
NSRange range = [book.name rangeOfString:searchText options:NSCaseInsensitiveSearch];
// is very very slow
if (range.location != NSNotFound)
{
[self.filteredListContent addObject:book];
}
}
}
Where i must insert NSPredicate, into our out the "for"?
- (void)filterContentForSearchText:(NSString*)searchText
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name contains %#", searchText ];
self.filteredListContent = [NSMutableArray arrayWithArray:[listContent filteredArrayUsingPredicate:predicate]];
}
If filtering for instance NSArray, you can use
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"job == 'Programmer'"]
[listOfItems filterUsingPredicate:predicate];
if you want to make a fetch request use
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"title == %#", aTitle];
[request setEntity:[NSEntityDescription entityForName:#"DVD" inManagedObjectContext:moc]];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];
// error handling code
[request release];
EDIT:
ssteinberg's example is simple and good, just one note - you can modify an operator using the key characters c and d within square braces to specify case and diacritic insensitivity respectively. Example [NSPredicate predicateWithFormat:#"name contains[cd] %#", searchString];

problem with between predicate

when using an nspredicate ( a between predicate) i had an exception.
there is the code i used:
NSMutableArray *returnedArray=[[[NSMutableArray alloc]init] autorelease];
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *objEntity = [NSEntityDescription entityForName:#"Note" inManagedObjectContext:context];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:objEntity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"When" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[fetchRequest setSortDescriptors:sortDescriptors];
[sortDescriptor release];
NSPredicate *predicate1 = [NSPredicate predicateWithFormat:
#"self.Reunion==%#",reunion];
NSNumber *endOfEtape=[NSNumber numberWithInt:[etape.positionDepart intValue]+[etape.duree intValue]];
NSExpression *s1 = [ NSExpression expressionForConstantValue: etape.positionDepart ];
NSExpression *s2 = [ NSExpression expressionForConstantValue: endOfEtape ];
NSArray *limits = [ NSArray arrayWithObjects: s1, s2, nil ];
NSPredicate *predicate2=[NSPredicate predicateWithFormat: #"self.When BETWEEN %#",limits];
NSPredicate *predicate=[NSCompoundPredicate andPredicateWithSubpredicates:
[NSArray arrayWithObjects:predicate1,predicate2,nil]];
[fetchRequest setPredicate:predicate];
NSArray *notes;
notes=[context executeFetchRequest:fetchRequest error:nil];
[fetchRequest release];
and i had an 'objc_exception_throw' at the line on which i call "executeFetchRequest:" method.
I will be happy if you can help me.
Thanks.
Unfortunately, the BETWEEN operand is considered an aggregate function & these aren't supported by CoreData.
See Apple's Documentation
... consider the BETWEEN operator (NSBetweenPredicateOperatorType); its
right hand side is a collection containing two elements. Using just
the Mac OS X v10.4 API, these elements must be constants, as there is
no way to populate them using variable expressions. On Mac OS X v10.4,
it is not possible to create a predicate template to the effect of
date between {$YESTERDAY, $TOMORROW}; instead you must create a new
predicate each time.
Aggregate expressions are not supported by Core Data.
So you'll need to use a predicate like:
NSPredicate *predicate2 = [NSPredicate predicateWithFormat:
#"self.When >= %# AND self.When <= %#", etape.positionDepart, endOfEtape];
(assuming positionDepart and endOfEtape are of type NSString)

NSPredicate - Not working as expected

I have the following code in place:
NSString *mapIDx = #"98";
NSLog(#"map id: %#", mapIDx);
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"WayPoint" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
//NSPredicate *predicate = [NSPredicate predicateWithFormat:#"waypoint_map_id=%#", mapIDx];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"waypoint_map_id==%#", mapIDx];
[request setPredicate:predicate];
NSError *error;
listArray = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
[request release];
int arrayItemQuantity = [listArray count];
NSLog(#"Array Quantity: %d", arrayItemQuantity);
// Loop through the array and display the contents.
int i;
for (i = 0; i < arrayItemQuantity; i++)
{
NSLog (#"Element %i = %#", i, [listArray objectAtIndex: i]);
}
/*
NSInteger *xCoordinate = listArray[1];
NSInteger *yCoordinate = listArray[3];
NSLog(#"xCoordinate: %#", xCoordinate);
NSLog(#"yCoordinate: %#", yCoordinate);
CLLocationCoordinate2D coordinate = {xCoordinate, yCoordinate};
MapPin *pin = [[MapPin alloc]initwithCoordinates:coordinate];
[self.mapView addAnnotation:pin];
[pin release];
*/
[listArray release];
As you can see I'm trying to select specific objects from my database, anything with a waypoint_map_id of 98, but the NSPredicate is not working as I expected. Zero objects are getting selected.
Anyone any thoughts ?
The predicate with format does not covert the string "98" to a number. Instead it does
waypoint_map_id == "98"
... which is looking for string attribute. Change the predicate to:
NSInteger mapIdx=98;
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"waypoint_map_id==%d", mapIDx];
... which returns a predicate of:
waypoint_map_id == 98
Assuming that you definately have that object in your database, try adding quotes around the value?
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"waypoint_map_id==\"%#\"", mapIDx];
(clutching at straws!)
Your prediacte looks fine so I would instantly start to suspect the bug is somewhere else :
Is there definintely a waypoint with that id?
Is listArray nil i.e. something else has gone wrong with the request?
You don't check to see what the error is - perhaps that will give you more information?
NSError *error = nil;
NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];
[request release];
if (nil == results || nil != error)
NSLog(#"Error getting results : %#", error);
listArray = [results mutableCopy];
Hope that's helpful at all!
Problem solved:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"waypoint_map_id contains[cd] %#", mapIDx];
[request setPredicate:predicate];