Need Help Setting Up Fetch Predicate - iphone

I am unsure as to what to use for the YourNameVariable. I think it needs to be an instance of Routine (or maybe the name property of Routine) but how do I create this? I am using a UITableView.
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Exercise" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
[request setPredicate: [NSPredicate predicateWithFormat: #"routineExercises = %#", yourVariableNameHere]];
NSLog(#"After managedObjectContext: %#", managedObjectContext);
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
// Handle the error.
}
[mutableFetchResults release];
[request release];
Here is my data model:
And also, should I be putting this in viewDidLoad or in the fetchResultsController's method?

You don't need a fetch if you already have the Routine objects. You just ask the Routine object for the contents of its routineExercises relationship.
You use fetches when you don't have an object to start with. If you already have an object, then you walk it's relationships to find it's associated objects. Fetching objects that are already in a relationship defeats the purpose of having relationships in the first place.

Related

mutating method sent to immutable object with userInfo (null)

I want to clear all the data by fetch all records and delete them one by one:
- (void) clear{
for (Program *program in [self getAllProgram]){
[managedObjectContext deleteObject:program];
}
if (![managedObjectContext save:&error])
{
NSLog(#"Problem deleting program: %#", [error localizedDescription]);
}
}
- (NSArray *)getAllProgram{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Program"inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat: #"freq = %#", self.freq];
[request setPredicate:predicate];
// Order the events by creation date, most recent first.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"sid" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptor release];
[sortDescriptors release];
NSError *error = nil;
return [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
}
The error is
CoreData: error: Serious application error. Exception was caught
during Core Data change processing. This is usually a bug within an
observer of NSManagedObjectContextObjectsDidChangeNotification.
-[__NSCFSet removeAllObjects]: mutating method sent to immutable object with userInfo (null)
Who can tell me the reason or tell me the one good practice ? thanks!
I suppose you have a fetched results controller somewhere. Set that controller's delegate to nil during the delete. I usually actually set the whole FRC to nil and update my whole data display after a large data change.
If that is not feasible, handle this case in the notification handler, like
if (!userInfo) return;

Search Through Core Data

All,
I have a core data entity, CreditCard, and each entity has four values.
So, what I need to do is search through ALL of my CreditCard entities and find the one with a property pocketNum that is equal to whatever value the user puts in, and then return it so I can pull necessary values from it.
How would I do this?
Thanks,
James
Try NSFetchRequest with NSPredicate:
// 'moc' is your NSManagedObjectContext instance
// 'yourPockerNum' is what you want to find
NSEntityDescription *entity = [NSEntityDescription entityForName:#"CreditCard" inManagedObjectContext:moc]
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = entity;
request.resultType = NSDictionaryResultType;
request.predicate = [NSPredicate predicateWithFormat:#"pocketNum == %#", yourPocketNum];
NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];
// do something with results

How to link existing values in a 1 to many relationship in core data?

I am trying to link a value that's already in category to the wod entity. Since I do want to call a new record for each record of wod for a category. Not sure how to do this. I was thinking of using predicate but I am not exactly sure how to link it from a fetch request.
this is what my schema looks like:
Here's the code that tries to link them together:
NSManagedObjectContext *context = [self managedObjectContext];
Wod *wodInfo = [NSEntityDescription
insertNewObjectForEntityForName:#"Wods"
inManagedObjectContext:context];
[wodInfo setValue:#"Frank" forKey:#"name"];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:#"Categories"
inManagedObjectContext:context]];
[request setPredicate:[NSPredicate predicateWithFormat:#"(name == %#", #"Time"]];
// This is the part where i am unsure, since i am not exactly sure how to link them up
Category *category = reques
wodInfo.category =
NSError *error;
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
Any help would be greatly appreciated.
NSError *error = nil;
NSArray *categories = [context executeFetchRequest:request error:&error];
Category *category = [categories lastObject];
wodInfo.category = category;
Be careful about your call to [context save:&error]. You are passing the address of the error variable, which is not initialized in your code and will refer to a random address, which might lead to weird errors in your application. I would recommend setting it to nil before passing it to the save: method.

NSFetchRequest autoreleased with no pool in place - just leaking

First off I have to say this website and its members are amazing in their responses. Most helpful. thank you.
Secondly, I am troubleshooting the following error while troubleshooting an iPhone/iPad app that I am working on:
NSFetchRequest autoreleased with no pool in place - just leaking.
the culprit code seems to be
NSFetchRequest *request = [[NSFetchRequest alloc] init];
found in this method
-(NSArray *)searchDatabase:(int)uniqueID withPredicate:(NSString *)pred{
NSLog(#": DetailViewController/searchDatabase() method...executing. ");
NSLog(#": DetailViewController/searchDatabase() pred = %#",pred); // returns ParentID
NSError *error = nil;
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Directory" inManagedObjectContext:self.managedObjectContext];
//: moved above line
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"%#=%#", pred, [NSNumber numberWithInt:uniqueID]]];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setReturnsObjectsAsFaults:NO];
[request setEntity:entity];
[request setPredicate:predicate];
//: get the session and update the record with the time it ended
NSArray *mutableFetchResults = [self.managedObjectContext executeFetchRequest:request error:&error];
NSLog(#": DetailViewController/searchDatabase() mutableFetchResults = %#",mutableFetchResults);
[request release];
[error release];
NSLog(#": DetailViewController/searchDatabase() method...terminating.");
return mutableFetchResults;
}
I am not sure if the release statements are properly set up, but even still I am unsure while the error shows up in the first place. I am a little new to objective c, and at compile time the application did not indicate any errors (the message shows up at runtime).
If anyone can help me out with this, it would be most appreciated.
thanks
Edward

persistance in iPhone Core Data

I'm trying to use core data to write a series of persistent data (NSManagedObjects) to sqlite and then read that series in to an application. I have managed to write and read a single record during a single session, but everytime I reload the app the previous data is not loaded (and sqlite manager recognizes tables but does not recognize any entries in the tables).
here is some of the core data logic:
in applicationDidFinishLaunching: i set managedObjectContext property of 3 controllers
inputControl.managedObjectContext = context;
reportControl.managedObjectContext = context;
logControl.managedObjectContext = context;
then in inputControl I add Event NSManagedObjects, such as
[event setDateCreated:[NSDate date]];
and in logControl I read the event logs
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Event" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"dateCreated" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
NSError *error;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
NSLog(#"Error fetching from DB");
}
int i;
NSLog(#"size of DB: %d",mutableFetchResults.count);
for (i=0; i<mutableFetchResults.count; i++)
NSLog(#"event %d: %#",i,[mutableFetchResults objectAtIndex:i]);
[mutableFetchResults release];
[request release];
When I run this code I see "size of DB:" as always set to '1'. managedObjectModel, managedObjectContext and persistentStoreCoordinator, are being handled in standard way.
Any assistance would be much appreciated
thank you
Peyman
Are you saving your managedObjectContext?
NSError *error = nil;
if (![context save:&error]) {
// Handle the error
}
You can fetch objects you've placed into your context, but unless you save the context to the persistant store, they won't be available next time.
Where are your calls to save? Is it possible you're not flushing to the NSPersistentStoreCoordinator?
I found the problem. The context was not saving (and I was not handling the error) because a mandatory property was not being set before saving (error 1520).
thank you all for your help
Peyman