Retrieve NSString from core-data error - iphone

The app needs to retrieve data from core-data then compare one of the values with an IF STATEMENT
MyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *getDetails = [NSEntityDescription entityForName:#"Detail" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:getDetails];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(genID = %i)", genID];
[request setPredicate:pred];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:#"genID" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sort]];
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
for (NSManagedObject *oneObject in objects) {
NSString *type = [oneObject valueForKey:#"type"];
if (type == #"straight") {
NSLog(#"straight");
//straight logic removed
}else if (type == #"Left") {
NSLog(#"Left");
//Left logic removed
}else {
NSLog(#"Else");
//Else logic removed
}
}
The issue is that it never goes into "straight" or "left" always the ELSE. Stepping through the code I can see that values do match straight and left, even dumped them into a log file shows them fine. What is wrong?

You need to compare strings using isEqual: or isEqualToString: or compare:.
For instance:
NSString *type = [oneObject valueForKey:#"type"];
if ([type isEqualToString:#"straight"])
// etc.
Search StackOverflow for "NSString equal" or "NSString compare" if you need more explanation. You aren't anywhere near the first person to ask this question, and you definitely won't be the last.

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

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.

problem with NSSortDescriptor .i am sorting the in ascending order(alphabetical order)

I am using NSSortDescriptor to sort the custom objects with key bandName, but I am not getting the output in alphabetical order. How do I fix that?
-(void)getdetails
{
NSLog(#"in getdetail method");
SongRequestAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context1 = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"AddToFav" inManagedObjectContext:context1];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSError *error;
NSMutableArray *array_new=[[NSMutableArray alloc]init];
[array_new addObjectsFromArray:[context1 executeFetchRequest:request error:&error]];
//[self.fetchedObjects addObjectsFromArray:[context1 executeFetchRequest:request error:&error]];
[request release];
**NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:#"bandName" ascending:YES] autorelease];
NSMutableArray *sortDescriptors = [NSMutableArray arrayWithObject:sortDescriptor];
//self.fetchedObjects=
[array_new sortedArrayUsingDescriptors:sortDescriptors];
[self.fetchedObjects addObjectsFromArray:array_new];
[array_new release];**
for (int i=0; i<[self.fetchedObjects count];i++)
{
NSManagedObject
*addfav=[self.fetchedObjects objectAtIndex:i];
addFavObject *addfavobject=[[addFavObject alloc]init];
addfavobject.bandImagePath=[addfav valueForKey:#"bandImagePath"];
addfavobject.bandId=[addfav valueForKey:#"bandId"];
addfavobject.bandName=[addfav valueForKey:#"bandName"];
addfavobject.songId=[addfav valueForKey:#"songId"];
addfavobject.songListId=[addfav valueForKey:#"songListId"];
addfavobject.songName=[addfav valueForKey:#"songName"];
addfavobject.bandRealName=[addfav valueForKey:#"bandRealName"];
addfavobject.biography=[addfav valueForKey:#"biography"];
NSLog(#"addto fav object biography is %#",addfavobject.biography);
[self.addTofavObjectArray addObject:addfavobject];
[addfavobject release];
}
//NSArray *reverse = [[self.addTofavObjectArray reverseObjectEnumerator] allObjects];
// [self.addTofavObjectArray removeAllObjects];
// [self.addTofavObjectArray addObjectsFromArray:reverse];
NSLog(#"self.addTofavObjectArray is %#",self.addTofavObjectArray);
NSLog(#"FETCHED OBJECTS count is %d",[self.fetchedObjects count]);
}
sortedArrayUsingDescriptors: doesn't sort in place the array it was sent to. It returns a new array with the objects sorted. It should work with:
NSArray *sortedArray = [array_new sortedArrayUsingDescriptors:sortDescriptors];
[self.fetchedObjects addObjectsFromArray:sortedArray];
You don't need to do the sort separately like that though. You can give the sort descriptors to your fetch request and the array returned from executing it will be sorted. I'd highly recommend doing it this way instead of how you're doing it. So you can replace everything before the for loop with:
SongRequestAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context1 = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"AddToFav" inManagedObjectContext:context1];
NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:#"bandName" ascending:YES] autorelease];
NSMutableArray *sortDescriptors = [NSMutableArray arrayWithObject:sortDescriptor];
[sortDescriptor release];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
[request setSortDescriptors:sortDescriptors];
NSError *error;
NSMutableArray *array_new = [context1 executeFetchRequest:request error:&error];
if (!array_new)
{
NSLog(#"error: %#", error);
}
[self.fetchedObjects addObjectsFromArray:array_new];
[request release];
I also added in the check for array_new to print the error. You might want to add additional error handling there too.

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.

Example of how to make a data factory for core data access in cocoa (iPhone)?

I have been slowly learning iPhone development and seem to keep hitting walls where I can't figure out how to do what I want to do the right way :(
Basically, I want a class that handles all interactions with the data layer, for example, getting a mutable array of some list of objects from the data store.
This is pretty trivial in other languages where you have a garbage collector, but in Objective-C on the iPhone, I'm not sure what to do.
This is an example method on a DataFactory class we were creating. Note the comment on where we are not sure when to release....
- (NSMutableArray*)fetchAllDrivers{
NSMutableArray *results = [[NSMutableArray alloc] init];;
if (self.appDelegate != nil) {
NSManagedObjectContext *context = [self.appDelegate managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Person" inManagedObjectContext:context];
[request setEntity: entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"lastName" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects: sortDescriptor, nil];
[request setSortDescriptors: sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
NSError *error;
results = [[context executeFetchRequest:request error:&error] mutableCopy];
if (results == nil) {
//something went wrong
}
//Where should this be released??? Certainly not here!
[results release];
[request release];
}
else {
[NSException raise:#"Can't fetch b/c app delgate is nil!" format: #"!!!"];
}
return results;
}
Calling code, related to my comment:
NSMutableArray* arr = [dataFactory fetchAllDrivers];
[arr retain];
//Some code where we use arr
[arr release];
Following naming conventions, your fetchAllDrivers should return an autoreleased object.
- (NSMutableArray*)fetchAllDrivers
{
if (!self.appDelegate) {
// Big Problems Raise exception immediately if you want...
return nil;
}
NSManagedObjectContext *context = [self.appDelegate managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Person" inManagedObjectContext:context];
[request setEntity: entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"lastName" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects: sortDescriptor, nil];
[request setSortDescriptors: sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
NSError *error = nil;
NSMutableArray *results = [[NSMutableArray alloc] initWithArray:[context executeFetchRequest:request error:&error] copyItems:YES];
if (error) {
// Something went wrong
[results release];
// Error handling code here
[request release];
return nil;
}
[request release];
return [results autorelease];
}
NSMutableArray* arr = [dataFactory fetchAllDrivers];
[arr retain];
//Some code where we use arr
[arr release];
By convention, any object returned from the method of an external object is autoreleased. You don't need to retain them except in properties. If you only using arr in the local scope of the method then you don't need to retain/release it. It is autoreleased and will die after the end of the local scope.
If you need to have arr hang around inside the object. You should store it in a retained property:
#property (nonatomic,retain) NSMutableArray *arr;
... then use it with the self notation to ensure retention:
self.arr=[dataFactory fetchAllDrivers];
... then you need only release it in the class' dealloc method.
Having one object manage your data model is very good idea but it is not a "factory". Objective-c does not use factories like C++ and similar languages. Trying to think in those terms will lead to grief. The object should instead be thought of as a "controller" or "manager".