Can I construct a PFQuery that queries all classes? - objective-c

i have an ios application in which i create a number of different classes of PFObjects, and i use pinning to the local datastore to take care of situations when i don't have network connectivity.
i'd like to query the local datastore from time to time in order to get all the objects in the store, irrespective of class.
i haven't been able to do this yet. the following code works fine and finds all the items of class MyClass
PFQuery *localStoreQuery = [[PFQuery alloc] initWithClassName:#"MyClass"];
[localStoreQuery fromLocalDatastore];
NSArray *results = [localStoreQuery findObjects];
but the following gives the error [Error]: bad characters in classname: (null) (Code: 103, Version: 1.8.5)
PFQuery *localStoreQuery = [[PFQuery alloc] init];
[localStoreQuery fromLocalDatastore];
NSArray *results = [localStoreQuery findObjects];
i also tried putting in #"*" as the classname like so
PFQuery *localStoreQuery = [[PFQuery alloc] initWithClassName:#"MyClass"];
but this also fails
so...is there any way to generically grab all pinned items of all classes, or do i have to have a loop and query each class i am creating separately (ugh)?
any help much appreciated.

Unfortunately you cannot. Parse does not support multi-class queries. You'd have to do each one, or make a super class that contains pointers to the object you'd like.

Related

Access object of to-many relationship

I have an object with a to-many relationship. It goes Workout<-->>Workout Score. If I have the workout score, how can I access the workout? I am using Parse.com.
Assuming workoutScore is a PFObject, and has been retrieved, I have a relationship called whichWorkout on it. The object returned is the workout, however I cannot access it's properties. Am I doing something wrong?
// Assuming this score has been retrieved by a PFQuery
PFObject *workoutScore;
PFObject *actualWorkout = workoutScore[#"whichWorkout"];
// Now when I try to access a property of actualWorkout, I can't
NSString *name = actualWorkout[#"name"];
If I just query for the actual workout, the same code works. Is there any way to access properties of objects retrieved via pointer relationships using Parse?
If you are running a query on the workoutScore you should use [query include:#"workout"]. This will pull the object that is being pointed to (the actualWorkout) and get everything you need in one call
PFQuery query = [PFQuery queryWithClassName:#"WorkoutScore"];
[query includeKey:#"workout"];
[query findAllInBackground....
The other option is to call fetch on the actual workout. This will be a second call after you have fetched the workoutScore. If you know you are going to need the workout probably better to get it during the query with the include.
PFObject *actualWorkout = workoutScore[#"whichWorkout"];
// There are asynchronous versions of fetch too
// which would be recommended
[actualWorkout fetch];
// actualWorkout will now have its data.
NSString *name = actualWorkout[#"name"];
If WorkoutScore has a back pointer to Workout (it looks like it does from your code, called whichWorkout), then it's easy. When querying WorkoutScore, use includeKey: to aggressively fetch the related object:
[workoutScoreQuery includeKey:#"whichWorkout"];
If the many to many relationship is a PFRelation, you'll have to query it as a second step
PFRelation *relation = [parseObject relationForKey:#"relationName"];
PFQuery *query = [[relation query] findObjectsInBackground:...];
If the many to many relationship is just an array of pointers, you need to tell the query to include the actual data:
[workoutScoreQuery includeKey:#"whichWorkout"];

-[NSCFNumber count]: unrecognized selector

I've got some Core Data code that follows Apple's sample code precisely (the Fetching Attribute Values that Satisfy a Given Function example). I'm using it to get the max value of a field, so I can then increment it when I insert the next object of that entity type.
I couldn't get the code to work at all, until I switched my Store Type from NSXMLStoreType to NSSQLiteStoreType, then all of a sudden everything seemed to be working. However, that's not the case. I noticed that it would always return the same value, even when I inserted objects with a higher one. But, after I quit and reopened (and thus the data was persisted and read back in), it would update with the new inserts.
So then I started committing and saving after each insert. After the first "autosave" though, I get the error below (twice in a row):
-[NSCFNumber count]: unrecognized selector sent to instance 0x100506a20
This occurs (two times in a rows) when I execute the fetch request once:
NSArray *objects = [context executeFetchRequest:request error:&error];
Update
I ran my code through the Zombies instrument, and was able to take a look at the object which is getting the error. The call that runs malloc to allocate it is: -[NSUserDefaults(NSUserDefaults) initWithUser:]. Since I don't have any of my own defaults set, I don't know what object this could be.
Update 2
I searched through all of my code for "release" and commented out every release or autorelease that the static analyzer didn't complain about. I still got the errors. I even went so far as to comment out every last release/autorelease in my code, and still got it. Now I'm fairly certain my own code isn't over-releasing.
Update 3
This post seems to be having the same problem, but his solution doesn't make sense. He changed the result type from NSDictionaryResultType to NSManagedObjectResultType, which produces an incorrect result. Instead of getting back a single value (the max that I'm looking for, that returns back every object of my entity class in the managed object context.
Here are the top-most levels of the stack trace (when I have it break on the exception, the first time):
#0 0x7fff802e00da in objc_exception_throw
#1 0x7fff837d6110 in -[NSObject(NSObject) doesNotRecognizeSelector:]
#2 0x7fff8374e91f in ___forwarding___
#3 0x7fff8374aa68 in __forwarding_prep_0___
#4 0x7fff801ef636 in +[_NSPredicateUtilities max:]
#5 0x7fff800d4a22 in -[NSFunctionExpression expressionValueWithObject:context:]
#6 0x7fff865f2e21 in -[NSMappedObjectStore executeFetchRequest:withContext:]
#7 0x7fff865f2580 in -[NSMappedObjectStore executeRequest:withContext:]
I've seen this question on numerous forums elsewhere on the web, but no one has offered a workable solution. By popular request, I added my own code below. To explain slightly, my entity's name is Box and the property I'm trying to get the value of is "sortOrder", an Int 32 attribute.
NSManagedObjectContext *context = [MyLibrary managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"Box"
inManagedObjectContext:context]];
// Specify that the request should return dictionaries.
[request setResultType:NSDictionaryResultType];
// Create an expression for the key path.
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:#"sortOrder"];
// Create an expression to represent the function you want to apply
NSExpression *expression = [NSExpression expressionForFunction:#"max:"
arguments:[NSArray arrayWithObject:keyPathExpression]];
// Create an expression description using the minExpression and returning a date.
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
// The name is the key that will be used in the dictionary for the return value.
[expressionDescription setName:#"maxSort"];
[expressionDescription setExpression:expression];
[expressionDescription setExpressionResultType:NSInteger32AttributeType];
// Set the request's properties to fetch just the property represented by the expressions.
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];
// Execute the fetch.
NSError *error;
NSNumber *requestedValue = nil;
NSArray *objects = [context executeFetchRequest:request error:&error];
NSLog( #"objects: %#", objects );
if (objects != nil && [objects count] > 0) {
requestedValue = [[objects objectAtIndex:0] valueForKey:#"maxSort"];
} else {
[[NSApplication sharedApplication] presentError:error];
}
[expressionDescription release];
[request release];
NSLog( #"Max Sort Order: %#", requestedValue );
return requestedValue;
Apparently this is a known bug, that occurs when using an NSInMemoryStoreType data store. It seems it works fine using an NSSQLiteStoreType.
You can find the OpenRadar entry here
I filled a duplicate for this bug — I encourage people that encounter the same issue to do the same, to increase the likelihood this annoying behaviour gets documented (or even better, fixed).
When you have memory management issues (selectors being sent to the wrong instances is a sign of memory management issues), there are a number of things you can do:
Re-read the Cocoa memory management rules and make sure that you're following them.
Run the static analyser. This will often pick up places where you have neglected the memory management rules.
Try using NSZombieEnabled to find out whether [and when] you are sending messages to unallocated instances.
-[NSCFNumber count]: unrecognized selector sent to instance 0x100506a20 means, that you are calling count on a NSCFNumber object, but NSCFNumber doesnt have this method. So most likely count is send to a deallocated NSArray or NSSet object.
USE NSZombieEnabled = YES. It might tell you, what happens. Search SO for informations on how to set it.
This can also happen if a binding is not set correctly. For example, if you bind a matrix boolean value to "Content" instead of (or in addition to) "Selected Tag" in IB you can get this error.
If all else fails, disconnect all of your bindings and reconnect them one at a time to see which one is the culprit.
After experiencing exactly the same problem with exactly the same sample code, it finally worked for me after I put [request release] in.
You are using the key path: sortOrder in your path expression. At least for XML-Databases Core-Data cannot handle case-sensitive types. Change your path to sortorder (all lower-case)
You will probably stumble over further problems if you are using controller classes.

Entity is not key value coding-compliant for the key

if (win) {
// Game was won, set completed in puzzle and time
// Calculate seconds taken
int timeTaken = (int)([NSDate timeIntervalSinceReferenceDate] - self.gameStartTime);
int bestTime = [[self.puzzle valueForKey:#"bestTime"] intValue];
if (timeTaken < bestTime && bestTime != 0) {
[self.puzzle setValue:[NSNumber numberWithInt:timeTaken] forKey:#"bestTime"];
NSLog(#"Best time for %# is %#", [self.puzzle valueForKey:#"name"], [self.puzzle valueForKey:#"bestTime"]);
}
}
This is some code from an iPad game I am making and I am using Core Data for storing the levels. When a level is completed and won, I want to set the best time for that level. The time taken is calculated, and if it is better than the previous best time, I want to set it as the best time for the level.
This code fails on the 'int bestTime' line when it tries to retrieve the best time from self.puzzle which is an NSManagedObject from Core Data. The best time is stored as an Integer 32 in the Core Data model. It fails with a SIGABRT error.
'[<NSManagedObject 0x95334d0> valueForUndefinedKey:]: the entity Puzzle is not key value coding-compliant for the key "bestTime".'
I have searched online for reasons as to why this is happening and how to fix it, but nothing seems to have helped. There are other places where I access Integer values from the Core Data model and they work perfectly, although they are used to filter and sort queries.
I also don't know if the line where I set the value will work.
Any help on this would be greatly appreciated.
EDIT: This is the code that fetches an array of puzzles of which one is taken to be the above puzzle.
// Define our table/entity to use
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Puzzle" inManagedObjectContext:managedObjectContext];
// Setup the fetch request
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
// Set the filter for just the difficulty we want
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"difficulty == %d", difficulty];
[request setPredicate:predicate];
// Define how we will sort the records
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"sortid" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[request setSortDescriptors:sortDescriptors];
[sortDescriptor release];
// Fetch the records and handle an error
NSError *error;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
Ok, Firstly, I would like to thank everyone who suggested ideas. They may not have helped me solve the problem, but I learnt more about Core Data and it is always good to find out what I should be checking when things don't work.
I don't really know what the problem was. Until this morning I had Xcode open for about 5 days I think and yesterday I added the attribute 'bestTime' to the data model. I can only assume that over the 5 days, Xcode had become a little unstable and thought it was saved when it wasn't. I had checked that I had saved the model attributes, in fact I must have checked 3 or 4 times as well as my habit of hitting Command+S after any change I make.
Anyway, I rebooted my machine earlier today and when I started up Xcode a few minutes ago I realised that 'bestTime' was not in the model file. I added it, reset the settings on the iPad simulator and it worked.
Thank you all again for the help, sorry the solution wasn't more interesting and code based. Although it makes me feel better that my code wasn't the cause.
That managed object doesn't have an attribute named “bestTime”. According to the exception message, it definitely is a Puzzle, so you haven't declared an attribute named bestTime in your model (or you misspelled it or capitalized it differently).
I did solve the same problem by delete and create the data model again and clean then rebuild again.
I think the bug is caused by core data does not update some data inside sometimes.
I don't think there's enough information here to determine the cause. You might try reading the Core Data Troubleshooting Guide; one possible cause could be if you initialized this particular instance of Puzzle using plain init rather than initWithEntity.
If you added attribute bestTime to the model at the later time, you might have forgotten to put declaration and implementation for them in the connected Managed Object Class.
Try convenience actions provided in Design -> Data Model -> Copy Objective-C ... Method Declarations/Implementations to Clipboard (when editing your Model file).
If parsing JSON into a managed object, be sure you're using the coreDataPropertyName property rather than the json-key-name key from JSON. Easy to mix up when they're named so similarly.
This error was driving me nuts, and all because I was using image-url rather than imageURL.

iPhone - Create non-persistent entities in core data

I would like to use entity objects but not store them... I read that I could create them like this:
myElement = (Element *)[NSEntityDescription insertNewObjectForEntityForName:#"Element" inManagedObjectContext:managedObjectContext];
And right after that remove them:
[managedObjectContext deleteObject:myElement];
then I can use my elements:
myElement.property1 = #"Hello";
This works pretty well even though I think this is probably not the most optimal way to do it...
Then I try to use it in my UITableView... the problem is that the object get released after the initialization. My table becomes empty when I move it!
Thanks
edit: I've also tried to copy the element ([myElement copy]) but I get an error...
Maybe you can try to have two store coordinators in your project. One which have persistence, and the other with no persistence.
couldn't you just do
Element *myElement = [[Element alloc] init];
Then do with it whatever you want, presumably you will add it to an array so it says around for your UITableView.
Consider using transient objects --- that are handled by the managed object context like any other object, but not written to disk on a save operation. They are typically employed to model runtime-only objects, as I suspect you are trying to do.
Here is some info on them:
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CoreData/Articles/cdNSAttributes.html
http://2pi.dk/tech/cocoa/transient_properties.html
One option drawn from an answer to a similar question is initializing the NSManagedObject with a nil context:
Element *myElement = [[Element alloc] initWithEntity:entity
insertIntoManagedObjectContext:nil];
or
Element *myElement = [NSEntityDescription insertNewObjectForEntityForName:#"Element"
inManagedObjectContext:nil];
What I did was using an in-memory store. You can do it as described here: http://commandshift.co.uk/blog/2013/06/06/multiple-persistent-stores-in-core-data/

iPhone's Core Data crashes on fetch request

I'm using the following code to grab a few objects from SQLite store (which is a prepared SQLite db file, generated with Core Data on desktop):
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity: wordEntityDescription];
[request setPredicate: [NSPredicate predicateWithFormat: #"word = %#", searchText]];
NSError * error = [[NSError alloc] init];
NSArray * results = [[dao managedObjectContext] executeFetchRequest: request error: &error];
Eveyrthing seems to be setup properly, but executeFetchRequest:error: fails deeply inside Core Data (on NSSQLCore _newRowsForFetchPlan:selectedBy:withArgument) producing 256 error to the outside code.
The only kink I had setting up managedObjectContext is I had to specify NSIgnorePersistentStoreVersioningOption option to addPersistentStoreWithType as it was constantly producing 134100 error (and yes, I'm sure my models are just identical: I re-used the model from the project that produced the SQL file).
Any ideas?
P.S. Don't mind code style, it's just a scratch pad. And, of course, feel free to request any additional info. It would be really great if someone could help.
Update 1
Alex Reynolds, thanks for willingness to help :)
The code (hope that's what you wanted to see):
NSEntityDescription * wordEntityDescription; //that's the declaration (Captain Obviousity :)
wordEntityDescription = [NSEntityDescription entityForName: #"Word" inManagedObjectContext: ctx];
As for predicate – never mind. I was removing the predicate at all (to just grab all records) and this didn't make any differences.
Again, the same code works just fine in the desktop application, and that drives me crazy (of course, I would need to add some memory management stuff, but it at least should produce nearly the same behavior, shouldn't it?)
Can you add code to show how wordEntityDescription is defined?
Also, I think you want:
NSError *error = nil;
You may want to switch the equals symbol to like and use tick marks around the searchText field:
[request setPredicate: [NSPredicate predicateWithFormat: #"word like '%#'", searchText]];
NSPredicate objects are not put together like SQL, unfortunately. Check out Apple's NSPredicate programming guide for more info.