Reputation: 843
I am facing a problem when I am fetching data from Core data database in my iPhone application.
I am using this code (Line 1) which is working fine, here I am fetching data from a date:
Note: Datatype of date
is NSDate
and selectedDate
is also type of NSDate
.
Line1:
[NSPredicate predicateWithFormat:@"date == %@",selectedDate];
This code (Line 2) is also working fine When I am fetching data of a system:
Line 2:
[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"systemName == '%@'",selectedSystemString]];
But when I combined the above two predicates with this code (Line 3):
Line 3:
[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"(date == %@) AND (systemName == '%@')",selectedDate,selectedSystemString]];
And application crashed on Line 3, and this error message is displayed in console:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "(date == 2015-01-15 18:30:00 +0000) AND (systemName == 'A')"'
*** First throw call stack:
(0x26494c1f 0x33c9cc8b 0x270feb55 0x270fc9bd 0x270fc93d 0x9b263 0x9c143 0xa8815 0x29a69f97 0x29b1bc0f 0x299cdc4d 0x29949aab 0x2645b3b5 0x26458a73 0x26458e7b 0x263a7211 0x263a7023 0x2d75a0a9 0x299b31d1 0xb1e7d 0x3421caaf)
libc++abi.dylib: terminating with uncaught exception of type NSException
Upvotes: 1
Views: 1296
Reputation: 12023
try using compound predicate,
NSPredicate *datePredicate = [NSPredicate predicateWithFormat:@"date == %@",selectedDate];
NSPredicate *stringPredicate = [NSPredicate predicateWithFormat:@"systemName == %@",selectedSystemString];
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates: @[datePredicate, stringPredicate]];
compound predicate using andPredicateWithSubpredicates:
method is similar to AND
predicate, the solution using AND would be
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"date == %@ AND systemName == %@",selectedDate, selectedSystemString];
Upvotes: 3
Reputation: 52565
The difference between your first two lines is why the third one fails. (The second one is also incorrect but works because you're using strings.)
It's like using query parameters if you're familiar with SQL.
In line 1 you say, here's what I'm looking for with this parameter (which happens to be a date).
In line 2 you say, here's what I'm looking for. There are no parameters. It should be like this:
[NSPredicate predicateWithFormat:@"systemName == %@",selectedSystemString];
Line 3 fails because you convert the date into a string (which uses the description
method on NSDate
); your predicate has no parameters. It should look more like this:
[NSPredicate predicateWithFormat:@"(date == %@) AND (systemName == %@)",selectedDate,selectedSystemString];
Upvotes: 3