Core data select objects from an array - iPhone - iphone

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

Related

Sorting / Filtering an NSArray / NSMutableArray

More for my interest than anything else.
If you have an Class defined like so...
MyClass
-------
NSString *name
And you put a lot of them into an array (or mutable array). Then you can use a predicate like this...
[NSPredicate predicateWithFormat:#"name = %#", someValue];
to filter the array so that it only contains objects whose names are the value given.
Or sort descriptor like so...
[NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES];
to sort the array by the name field in ascending order.
My question is, if you have an array of strings (or of NSNumbers) can you use similar "format" predicates?
Say for instance you had the array...
#[#"Cat", #"Bat", #"Dog", #"Cow"];
Could you use a "predicateWithFormat" to filter this array of a "sortDescriptorWithKey" to sort it?
I know you can use blocks but just wondering if this is possible?
Sure, you can filter an array of strings, or anything else, with predicateWithFormat:. As for sorting, you would use sortedArrayUsingSelector:, and use whichever selector you want (compare:, caseInsensitiveCompare:, etc.). There are no keys in a simple array, so you couldn't use sortDescriptorWithKey.
A string does not have any keys to use your predicates on or to sort by. You can find every other possible way to sort an array in the apple docs.

Check if CoreData attribute is empty

I am hoping to find a way to check, if a CoreData attribute is empty. The attribute itself is of type binary data. If the attribute is empty then I could tell my class to download and save some data into this attribute.
According to CoreData Documentation, you should not keep fetching to see if objects exists. I am wondering if there is even a way to possibly do this? without breaking this 'law'?
This is my first attempt at using CoreData. I am adding it to my code afterwards, which is slightly more painful, but as a whole so far everything seems to be going okay. I just need to figure out a logical way of checking if attribute has values. If it doesn't then I need to download and save the new data, if it does then I just use what's in the attribute.
Update :
I just found this method in the CoreData framework that I have been reading though trying to catch a break on this. Not sure if it would help.. what do you guys think?
willAccessValueForKey: Provides support for key-value observing access
notification.
(void)willAccessValueForKey:(NSString *)key Parameters key The name of one of the receiver's properties. Discussion See
didAccessValueForKey: for more details. You can invoke this method
with the key value of nil to ensure that a fault has been fired, as
illustrated by the following example.
[aManagedObject willAccessValueForKey:nil];
Not sure really.. the things that I dont understand is Provides support for key-value observing access notification. ???
That notification is for when the value is going to be accessed.
If I understand you correctly, you are not wanting to see if an entity exists, but an attribute within the entity. So, I assume you have it marked as an optional attribute.
Let's say you have a binary data attribute called rawData. If you want to find all the #"MyEntity" objects in the database that do not have any data set for this attribute, you cn issue this fetch request.
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"MyEntity"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:#"rawData = nil"];
NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:0];

NSPredicate that calls test method to fetch results from Core Data

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.

NSPredicate with functions or selectors

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];

NSPredicate syntax question

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.