NSPredicate crash on CONTAINS? - ios

I'm trying to do a simple predicate filter on an array of objects.
The objects in the array have 2 properties, displayValue and value. I am trying to filter based on a search string and I get a crash.
NSPredicate *pred = [NSPredicate predicateWithFormat:#"displayValue CONTAINS[cd] %#", searchString];
NSArray *results = [_data filteredArrayUsingPredicate:pred];
what exactly is incorrect about this format that it causes a Can't use in/contains operator with collection 100 (not a collection) crash?

I was able to reproduce your problem. This happens if the displayValue of one of the objects
is not a NSString, but some different type.
From your error message, I assume that you assigned an NSNumber, for example
obj.displayValue = #100;
somewhere in your code. The "CONTAINS" predicate works only with strings, so you must assign
only string values to the property.
Therefore, you should define the type of the property as
NSString * instead of id, and check the assignments to that property.
If you really need to keep the id type and store different kinds of objects in that property,
then you cannot use the "CONTAINS" operator in the predicate. A direct comparison
with #"displayValue == %#" would work, however.
UPDATE: As a workaround, you could use the description method, which converts any object
to a string, in particular it converts a NSNumber to its string representation. So the following could work:
[NSPredicate predicateWithFormat:#"displayValue.description CONTAINS[cd] %#", searchString];
The drawback is that the exact description format is not documented.
Another solution could be to use a block-based predicate, where you can check the type
of each object and perform the appropriate comparison.

Related

IOS/Objective-C: NSPredicate and NULL values in core data fetch

I am trying to fetch items that do not have a value of 1 in an NSNumber attribute. Some of the items I want to fetch have never had the attribute set at all and therefore have a NSNull value. How can I fetch items that are not 1 but may be NSNull?
The attribute is an NSNumber and I am also a bit confused about whether I should be searching on 1 or #1.
The following code is excluding NSNull values when I want to include them:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"&hasserverid!=1"];
Thanks for any suggestions.
You can explicitly test for both cases with an OR:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"hasserverid != YES OR hasserverid == NULL"];
By the name of your property, I assume when you say 1 you're actually referring to the value true. Using YES in the predicate format instead of 1 makes your predicate more legible.

How to set predicate for a string attribute holding integer value in core data

How to set predicate for a string attribute holding integer value in core data to get the in-between values in integer.
I am using compound predicate for multiple conditions and a piece of code follows..
NSPredicate *categoryPredicate = [NSPredicate predicateWithFormat: #"rating >= %# AND rating <= %#",ratingFrom.text,ratingTo.text];
[compoundPredicateArray addObject: categoryPredicate ];
"rating" attribute is of type string in database. I need to get the rating between the given range in the ratingFrom & ratingTo textfields.
"1" to "10" should fetch all ratings in between 1 to 10.how can I achieve this, without changing the attribute type to number.
Any help appreciated..Thanks
i am not confirm but try this
convert your values in NSString and put this code
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"string CONTAINS[c] %#",searchText];
Ideally you should change this attribute to be a number rather than a string. But if that's not possible, the following should force CoreData (or rather SQLite) to treat it as a number:
NSPredicate *categoryPredicate = [NSPredicate predicateWithFormat: #"add:to:(rating,0) >= %d AND add:to:(rating,0) <= %d",ratingFrom.text.intValue,ratingTo.text.intValue];
you can try BETWEEN expression:
BETWEEN The left-hand expression is between, or equal to either of,
the values specified in the right-hand side. The right-hand side is a
two value array (an array is required to specify order) giving upper
and lower bounds. For example, 1 BETWEEN { 0 , 33 }, or $INPUT BETWEEN
{ $LOWER, $UPPER }. In Objective-C, you could create a BETWEEN
predicate as shown in the following example:
So your code should look like this:
NSPredicate *betweenPredicate =
[NSPredicate predicateWithFormat: #"rating BETWEEN %#", #[ratingFrom, ratingTo]];
ratingFrom, ratingTo should be NSNumber instances if rating is NSNumber.

NSPredicate for two NSNumber arrays

I have a bit of a hard time writing a predicate for my search functionality and thought you'd be bale to help. So basically I have two arrays of NSNumbers. I want my predicate to satisfy the following:
If a number's integerValue in array A matches any integerValue in array B.
I don't want to use any sort of loop for this solution. Here's what I have so far
ANY integerValue == ANY //how do I pass the entire array here and ask for the integerValue of each member?
The ANY operator will handle that.
Since it is a bit difficult to say from your question which of the arrays is "self" in normal predicate parlance, I'll write it without a self:
NSArray *arrayA = #[#2, #3, #7];
NSArray *arrayB = #[#2, #4, #9];
NSPredicate *pred = [NSPredicate predicateWithFormat: #"ANY %# IN %#", arrayA, arrayB];
Due to the lack of a "self", it will have to be evaluated with nil as the object, but that works fine:
BOOL matched = [pred evaluateWithObject: nil];
If you prefer to have a "self" in the predicate, you can just enter it:
NSPredicate *pred = [NSPredicate predicateWithFormat: #"ANY self IN %#", arrayB];
BOOL matched = [pred evaluateWithObject: arrayA];
The result is the same.
A small conceptual comment
The predicate above evaluates to true if any integer is included in both arrays, which is how I read your question.
This means that, conceptually speaking, you seem to be testing whether two sets of numbers intersect each other. NSSet's method intersectsSet: checks that, so another way to do the test would be to keep your numbers as sets and test for intersection:
matched = [setA intersectsSet: setB];
I know it's not precisely what you asked for (predicates and all) but another way is to use NSArray's - (id) firstObjectCommonWithArray:(NSArray *)otherArray, which would return nil if no common object can be found.
BOOL arraysIntersect = [array1 firstObjectCommonWithArray:array2] != nil;
One caveat though is that it would use its own object equality rules when comparing two objects, meaning if two objects are NSNumber instances, it will compare them using NSNumber's compare: method. But the same goes for the predicate-based solution proposed so far.

Error when trying to sort array using predicates

I'm struggeling with an error occurring when trying to populate an array with the filtered results of another array.
I've defined a global array named allArray in the .h-file, this array is containing about 100 objects. Then, I want the user to be able to search for a specific object, and I've tried to develop it using predicates:
-(IBAction)searchChanged:(id)sender {
//The searchfield's value has been changed.
NSString *searchString = searchField.text;
NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:#"self CONTAINS[c] %#", searchString];
NSMutableArray *tempSearchArray = [allArray filterUsingPredicate:searchPredicate];
[filteredArray removeAllObjects];
[filteredArray addObjectsFromArray:tempSearchArray];
}
I end up getting an error when I create tempSearchArray.
Initializing 'NSMutableArray *__strong' with an expression of
incompatible type 'void'
filterUsingPredicate doesn't return an array, it returns nothing(void).
From the description:
"Evaluates a given predicate against the array’s content and leaves only objects that match"
You should instead use:
filteredArrayUsingPredicate
As the Docs will tell you, filterUsingPredicate has a void return value.
See here:
NSMutableArray Class reference
That means that you cannot assign that return value to another array.
You need to use this method on the original array, along the lines of
[allArray filterUsingPredicate:somePredicate];
arrArray will be stripped of any elements that dont match the predicate.
Now proceed with these results as you wish.
Have Fun
filterUsingPredicate returns a void and not an array. You might want to consider using a filteredArrayUsingPredicate instead

NSArray with NSPredicate using NOT IN

I have an NSArray that I want to filter out certain objects using an NSPredicate, I was hoping I could use NOT IN since I saw that I can easily do an IN.
So I have my array:
self.categoriesList
Then I get the values I want to remove:
NSArray *parentIDs = [self.cateoriesList valueForKeyPath:#"#distinctUnionOfObjects.ParentCategoryID"];
This gives me a list of ParentCategoryID's for categories I DO NOT want to display, so I figure I can use an NSPredicate to remove them:
self.cateoriesList = [self.cateoriesList filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"CategoryID NOT IN %#",parentIDs]];
This fails:
reason: 'Unable to parse the format string "CategoryID NOT IN %#"'
If I wanted to use just IN that works perfectly of course.
What about NOT (CategoryID IN %#)?
How about using NONE?
[NSPredicate predicateWithFormat:#"NONE CategoryID IN %#", parentIDs];

Resources