how to create a NSManagedObject - iphone

I am currently reading my coredata like this
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Manuz" inManagedObjectContext:__managedObjectContext];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [__managedObjectContext executeFetchRequest:fetchRequest error:nil];
NSManagedObject *myinfo = [NSManagedObject alloc]
for (NSManagedObject *info in fetchedObjects) {
[self startTheParsingProcess:[info valueForKey:#"manu"]];
}
I am having some issues with my for statement, its execuing several time and I am not sure why its doing that.. and come to think of it I don't really need it..
I am hoping there is an alternative solution to this where I just initalize the NSManagedObject and then add it to the method call I do in that for statment...
So I guess something like this
NSManagedObject *info = [[NSManagedObject alloc] init]; //this is obviously wrong..
[self startTheParsingProcess:[info valueForKey:#"manu"]];
any help would be awesome!

Do not create a NSManagedObject using alloc & init. If you want to create an instance of an entity "Manuz", you would do so by inserting a new Manuz object into the managed object context.
NSManagedObject *newManuz = [NSEntityDescription insertNewObjectForEntityForName:#"Manuz" inManagedObjectContext:context];

Related

Coredata not working while popping the view controllers

I have 2 viewcontrollers (say A & B) ... I have some records in A now I want to edit the data in the core data.... For that I push the navigation controller to B.. There I edit the data in core data.. Itz working fine.. This the code I use for editing..
NSManagedObjectContext *managedContext = [self managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"CamImage" inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
// Set the predicate -- much like a WHERE statement in a SQL database
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name == %#", xapp.patientName];
[request setPredicate:predicate];
// Set the sorting -- mandatory, even if you're fetching a single record/object
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
sortDescriptors = nil;
NSError *error;
// Request the data -- NOTE, this assumes only one match, that
// yourIdentifyingQualifier is unique. It just grabs the first object in the array.
CamImage *event = [[managedObjectContext executeFetchRequest:request error:&error] objectAtIndex:0];
[event setMedicineImage:butImage];
[event setMedicineName:text.text];
[event setQuantity:[jst objectAtIndex:0]];
[event setUnit:[jst objectAtIndex:1]];
[event setMeal:meal];
request = nil;
NSMutableArray *mutableFetchResults = [[self.managedObjectContext executeFetchRequest:request1
error:&error] mutableCopy];
if (mutableFetchResults == nil) {
// Handle the error.
}
// Set self's events array to the mutable array, then clean up.
[self setCamImage:mutableFetchResults];
NSLog(#"AddMedicineArray:%#",camImage);
[self.navigationController popViewControllerAnimated:YES];
}
In above code I edited the data and fetched it once again..I can found the data got edited properly.. After editing I pop to B.. In the viewwillappear method I once again fetch the data.. But I find the old records only... Once I run the app again I found the edited data got fetched properly.. Here is the code in viewwillappear
-(void)viewWillAppear:(BOOL)animated{
camImage=Nil;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"CamImage" inManagedObjectContext:self.managedObjectContext];
[request setReturnsObjectsAsFaults:NO];
[request setEntity:entity];
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
// Handle the error.
}
// Set self's events array to the mutable array, then clean up.
[self setCamImage:mutableFetchResults];
viewWillAppear is not being called, because the parent view remains in the view hierarchy the whole time. Instead, implement navigationController:willShowViewController:animated: See this question: iOS 5 viewWillAppear not being called when popping a NavigationController

How To Get Name From NSArray

I have a NSFetchRequest to search of core data entities. It finds them fine, but I want to set the cell's text to the entity's name attribute.
I currently have this but I am setting the object itself to the title, instead of the name attribute, how can I fix this?
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Routine" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
self.routineArray = results;
[fetchRequest release];
cell.textLabel.text = [self.routineArray objectAtIndex:indexPath.row];
Try :
cell.textLabel.text = [[self.routineArray objectAtIndex:indexPath.row] name];
EDIT
If your Routine instances are in routineArray (given that name, I suppose) :
// get the Routine instance
Routine *r = [self.routineArray objectAtIndex:indexPath.row];
// now you got your instance, set anything you want on r...
// ...
// and then set its name as the text for textLabel using previous instruction

Quick Question About Fetch And NSObject

I have the following code that fetches a Session object for a particular Exercise object.
This fetch loads data into my UITableView.
The count is fine, I just need a way to extract the Session.timeStamp property so I can set it to UITableViewCell's textLabel property.
Does anyone know how?
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"name == %#", exercise.name]];
NSEntityDescription *sessionEntity = [NSEntityDescription entityForName:#"Exercise" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:sessionEntity];
NSError *error = nil;
NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
NSMutableArray *mutableSessionArray = [NSMutableArray array];
for (Exercise *ex in results) {
Session *session = [ex exercises];
[mutableSessionArray addObject:session];
}
self.sessionArray = [NSArray arrayWithArray:mutableSessionArray];
Call timestamp property of your mananged object subclass or call valueForKey.

Memory leak when retrieving data from database

Hey, I've created a custom retrieval method for database access:
+(NSArray*) recordsForTable:(NSString *)table predicate:(NSPredicate *)prd{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:table inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:prd];
NSArray *records = [managedObjectContext executeFetchRequest:fetchRequest error:nil];
[fetchRequest release];
return records;
}
i then use the above method in this method:
-(NSArray *)tableViewControllerData{
NSNumber *savedBool = [[NSNumber alloc] initWithBool:YES];
NSString *onlyGetSavedVisitObjects = [NSString stringWithFormat:#"bolSaved=%#", savedBool];
[savedBool release];
NSMutableArray *data = [[[CoreDataAccess recordsForTable:#"LPVisit" stringPredicate:onlyGetSavedVisitObjects] mutableCopy] autorelease];
NSSortDescriptor *dateDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"dteVisitDate" ascending:NO];
NSArray *descriptors = [NSArray arrayWithObjects:dateDescriptor, nil];
[data sortedArrayUsingDescriptors:descriptors];
return data;
}
The trouble am having is that when the user makes changes to the LPVisit table and recall this method to show those changes it crashes the application.
[EDIT]
The exception it produces is:
-[__NSArrayM objectID]: unrecognized selector sent to instance 0x4dac1f0
I believe the error is at line:
NSMutableArray *data = [[[CoreDataAccess recordsForTable:#"LPVisit" stringPredicate:onlyGetSavedVisitObjects] mutableCopy] autorelease];
If I remove the autorelease, I get a memory leak but the application doesn't crash.
Does anyone have any insights, thanks in advance
Is it possible that the mutable copying is throwing the exception because *records is nil? This might happen if #"bolSaved=%#" is a typo and should be #"boolSaved=%#".

get NSString from NSFetchRequest issue

I'm using Core Data and I need to loop thru the result of the request, create several custom objects in the loop and store them in a NSMUtableArray, so I can send it to another view to feed a UI component. This is what I'm doing:
NSMutableArray *persons = [[NSMutableArray alloc] init];
NSError *error = nil;
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Person" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
ToggleButtonInfo *btn = [[ToggleButtonInfo alloc] init];
NSString *personName = [NSString stringWithFormat:#"ww %#", [info valueForKey:#"name"]];
NSLog(#"pn: %#", personName);
[btn setButtonInfo:personName];
[persons addObject:btn];
}
[fetchRequest release];
return persons;
The loop is working just fine, the information is there. The problem is that I get a "EXC_BAD_ACCESS" in my component if I use:
[info valueForKey:#"name"]
if I do something like this:
[btn setButtonInfo:#"something else here"];
everything works fine. So it looks like info is been de-allocated and that is causing the error, right? I try creating the scring using stringWithFormat but it doesn't work, same error.
An ideas?
Where do you get the EXC_BAD_ACCESS? I assume it's later when you're displaying the button? -setButtonInfo: probably isn't retaining, or you're over-releasing somewhere else.
Note that you're leaking btn in this code.