Could I do the following Predicate in Swift 4 to the following string 'name':
let predicate = NSPredicate(format: "name.dropLast() = %#", searchText)
Basically, could I add the extension 'dropLast()' inside the predicate? If not, what is an alternative?
"Could I do the following"
No. NSPredicate comes with its own completely specified language. Predicate strings must conform to that language; otherwise, they cannot be parsed.
"If not, what is an alternative?"
An alternative to do what? You are not telling us anything about the goal here. For example, instead of calling NSPredicate(format:), you might be able to call NSPredicate(block:) which lets you write the predicate test in Swift code. But you can't do that in all situations. And you have not said what your situation is.
Related
I have this error: XCTAssertTrue failed: throwing "[<XCElementSnapshot 0x7fea978b1a10> valueForUndefinedKey:]: this class is not key value coding-compliant for the key staticTexts."
Here is the code:
let predicate = NSPredicate(format: "(self.staticTexts[%#].exists == true) AND (self.staticTexts[%#].exists == true)", message, nameString)
XCTAssert(app.collectionViews.childrenMatchingType(.Cell).elementMatchingPredicate(predicate).exists)
Error is thrown on the second line.
I have looked at other answers on SO with the same error, and it's mostly caused by having a variable of a different class, however I don't see the possibility for this error here. Also, I checked to see that the predicate is formatted correctly.
How can I get rid of this error?
Make sure that your staticTexts property is dynamic or otherwise available to objc (by marking it #objc for instance). Swift will not generate KVC-compliant accessors unless it thinks it needs to.
Alternately, use something other than NSPredicate here. Making a property dynamic when it's not needed has a performance cost, which is why Swift doesn't do it automatically. So marking it dynamic just so a unit test can access it may be a poor tradeoff.
Apparently, the error goes away when I apply the predicate to static texts vs. the cells and then try to access the static texts inside the predicate. So for example,
let predicate = NSPredicate("self.title like %#", message)
app.descendantsMatchingType(.StaticText).elementMatchingPredicate(predicate).exists
would get rid of the error.
I am not quite sure how to word this question without explaining what I am trying to do.
I have a managed object context filled with (essentially) circles that have an x,y coord for the center point and a radius.
I would like to construct a predicate for my core data retrieval that will find all circles that overlap with a given circle.
I can write a boolean method that tests this and returns true or false, but my problem is that I don't know how to call this testing method in my predicate.
in pseudo-code, I am trying to do this:
NSPredicate *pred = [NSPredicate (if [testOverlapWithCenterAt:centerOfGivenObjectInContext andRadius:radiusOfGivenObjectInContext]);
Perhaps NSPredicate isn't even the best way to do this. Any help would be much appreciated.
You can use the predicateWithBlock instance method of NSPredicate. Give it a try.
I have a lot of people NSManagedObjects that I need filtering and was hoping to do it within the initial fetch instead of filtering the array afterwards. I've used selectors in predicates before, but never when fetching NSManagedObjects, for example I have all my employees and then i use this predicate on the NSArray...
[NSPredicate predicateWithFormat:#"SELF isKindOfClass:%#", [Boss class]]
...but now I want to do a bit more math based on different attributes of my objects. I thought I could do something like...
[NSPredicate predicateWithFormat:#"SELF bonusIsAffordable:%f", howMuchMoneyTheCompanyHas];
..where bonusIsAffordable: is a method of my Employee class and would calculate whether I can afford to pay them a bonus. But I get an error...
Unknown/unsupported comparison predicate operator type cocoa
Any ideas what I'm screwing up?
This gets a whole lot easier with Blocks:
NSPredicate *bossPred = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
return [evaluatedObject isKindOfClass:[Boss class]];
}];
You can execute arbitrary code in an NSPredicate only when qualifying objects in memory. In the case of a SQLite-backed NSPersistentStore, the NSPredicate is compiled to SQL and executed on the SQLite query engine. Since SQLite has no knowlege of Objective-C, nor are any objects instantiated, there's no way to execute arbitrary code.
For in-memory queries (against a collection or an in-memory or atomic Core Data store), have a look at NSExpression, particular +[NSExpression expressionForFunction:selectorName:arguments:] and +[NSExpression expressionForBlock:arguments:]. Given such an expression, you can build an NSPredicate programatically.
Your predicate string doesn't tell the predicate object what to do. The method presumably returns a boolean but the predicate doesn't know what to compare that to. You might as well have given it a predicate string of "TRUE" and expected it to know what to do with it.
Try:
[NSPredicate predicateWithFormat:#"(SELF bonusIsAffordable:%f)==YES", howMuchMoneyTheCompanyHas];
is the syntax for the line of code below correct?
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"type == %#",selectedAnimalType];
I want the 'selectedAnimalType' string to be used in a search to display the the user selected.
I ran an NSLog statement for the %# object and it returned what I wanted
NSLog(#"%#",selectedAnimalType);
thanks for any help.
Whether it works depends on what class type and selectedBirdType are. If they are both objects like NSStrings or NSNumbers it will work fine. If not you may have problems.
To see exactly what the predicate is just log the predicate object itself. It will print out the exact, populated i.e. with variables substituted, predicate so you can see exactly what is going on.
I was wondering if I could select objects based on a predicate with an array... for example
Code:
[NSPredicate predicateWithFormat:#"id=%#", arrayOfID];
Will it work? If no, how can I do it?
Best
The correct predicate would be
[NSPredicate predicateWithFormat:#"id IN %#", arrayOfID];
Assuming that arrayOfId contains objects of the same type as id (e.g. NSNumbers or NSStrings).
Yes, of course you can do it.
Sounds like you need a bit of grounding in Core Data. I found the following tutorial really useful in getting me off the ground with Core Data:
http://iphoneinaction.manning.com/iphone_in_action/2009/08/core-data-part-1-an-introduction.html