Iphone Core data question - iphone

I have set up the application with 2 entity, called Category1 and category2. There is a to-many relationship between category1 and category2. When a cell is pushed in tableview (category1), a new tableview will display all category2 cells related to category1. Here is what an example:
I have two category1 items in the first tableview, called Food and Snacks. Item "Food" have a subcategory (category 2) that contains 5 different kinds of food. Item "Snacks" have a subcateogry (category2) that contains 10 different snacks.
So when i push the food item (category1) I just want the food item to be loaded (5 of them). Right now, I can see all 5 of the food item in the tableView, plus the 10 items from the "snacks" category2.
I use this code in category2:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Folder" inManagedObjectContext: tag.managedObjectContext];
[request setEntity:entity];
//NSMutableSet *filtered = [tag mutableSetValueForKey:#"folders"];
// Order the events by creation date, most recent first.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"creationDate" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptor release];
[sortDescriptors release];
// Execute the fetch -- create a mutable copy of the result.
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[tag.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil)
{
// Handle the error.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1); // Fail
}
// Set self's events array to the mutable array, then clean up.
[self setTagsArray:mutableFetchResults];
[mutableFetchResults release];
[request release];
need help !
thanks in advance!

First a bit of advice: In your root table view you should be using a NSFetchedRequestController to manage the top level objects. Take a look at the Recipes application in Apple's sample code for a demonstration.
As for the primary issue you are seeing, what you should do is push the category1 object to the child view controller. The child view controller can then query the that category1 object for all of its children to display. No fetch is required on the child view controller because you already have the parent object. Again, the recipe example app from Apple will demonstrate this quite clearly for you.

Do it in views, so there are two views for the subcategories, one for food, one for snacks. Then on the first table view have it set so when you tap on food, it'll go to the food view, same with the snacks. If you can't get it working try with UIButtons. What I do is if all else fails, go to UIButtons :) If you need help getting it to switch views I made an example as part of my 25 apps in august project, you can find my example here: http://appeveryday.wordpress.com/2009/08/02/app-3/

Related

Sections from already queried Entity

So i'm displaying some Entities in a UITableView. With clicking on a Cell i want to show other Entities that are already queried in a "to-many" Relationship.
For example i'm displaying all Classes of a School. Now i want to display all Students of a Class. This Students are already available as an NSSet under Class.students
Now i want to display the Students in different Sections following by their first Letter.
If i wanted to get them directly from CoreData, i would do something like
// init fetch request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Student" inManagedObjectContext:self.managedObjectContext];
// Search only specific students
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"class == %#", theClassThoseStudentsBelongTo];
[fetchRequest setPredicate:predicate];
// Generate it
NSFetchedResultsController *theFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:#"firstLetter"
cacheName:#"StudentTable"];
with this method i would get them nicely arranged into sections.
But i already have all students for a specific Class. is there a way to init a NSFetchedResultsController with a initialized NSSet or to do something equal?
Sure, i could arrange my NSSet manually but isn't there such a nice way like it is for a new query?
thanks in advance.
Please leave a comment if something is unclear.
I guess you only have 2 options: using NSFetchedResultsController or sorting the objects on your own.
NSFetchedResultsController & NSPredicate:
Pros: easy object deletition; notifications of model changes, e.g. during syncing
Cons: unnecessary refetch
NSSet & NSSortDescriptor
Pros: no refetch
Cons: complicated deletition; no notifications of model changes, e.g during syncing: you could be displaying a student that has already been deleted
you could use a NSPredicate which uses the reverse relationship (from your students back to the class)
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
...
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"class == %#", theClassThoseStudentsBelongTo];
[fetchRequest setPredicate:predicate];
NSFetchedResultsController *theFetchedResultsController = ...
The relationship of objects fetched by NSFetchedResultsController start out as faults and are only fetched when needed. This means that if we don't use the "Student" entities for the first tableView it will be lazily loaded only when we need it.
However, since you need to know the count of students the situation is a little more complicated since calling [class.students count] will fire the fault. (Calling the KVO #count will fire the fault also).
So you have two options:
managed an attribute called studentsCount in class that reflects the number of entities in students. Calling this attribute will not fire a fault on the relationship.
use countForFetchRequest:
NSFetchRequest *req = [[NSFetchRequest alloc] init];
[req setEntity:[NSEntityDescription entityForName:#"Student" inManagedObjectContext:context]];
[req setPredicate:[NSPredicate predicateWithFormat:#"class = %#", myClass]];
The second option performs a fetch, but a very efficient one, so maybe it's efficient enough - i didn't do performance tests so i can't really say.
By the way, if you're not sure whether or not the relationship fired a fault you can use the method hasFaultForRelationshipNamed.

CoreData DetailTableView BAD_ACCESS Error

Maybe I'm not going about showing a detail for a selected row using CoreData, but I can't figure out why I'm getting a "BAD_ACCESS" error. I've googled around and can't find what I'm looking for.
Basically I use CoreData to populate the data for a Table View. It retrieves all of the title attributes for all of the entities. When the user clicks on a row, I have a Detail View that needs to show the description for that entity. I think I need to make a new NSManagedObjectContext and a new NSEntityDescription for a new NSFetchRequest in my DetailViewController and then use a NSPredicate to say "where title = [user selected title]". I get an error when I select a row. See code:
- (void)viewDidLoad
{
// Do any additional setup after loading the view from its nib.
// Get the objects from Core Data database
Caregiver_Activity_GuideAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription
entityForName:#"Definition"
inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(title = %#)", self.title];
[request setPredicate:pred];
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil) {
NSLog(#"There was an error!");
// Do whatever error handling is appropriate
}
for (NSManagedObject *oneObject in objects) {
[definitionDescriptionTextView setText:[oneObject valueForKey:#"desc"]];
}
[objects release];
[request release];
[super viewDidLoad];
}
I comment out that code and everything works. But when I try to debug with breakpoints, nothing catches. So I'm more confused.
I know CoreData is probably overkill for what I'm doing but this is a learning app for me.
EDIT: I didn't include that I'm using a sqlite database that is pre-populated with the entities.
You can also download my project on my github page.
Normally, with a Core Data backed Master-Detail interface, you don't fetch for the Detail view.
When you select a row in the Master tableview, you are selecting a particular managed object instance. You then pass that managed object instance to the detail view. There is no need to refetch the object that you selected in the tableview.
A good example of this would be the Contacts app. The Master tableview would be a list of Contact objects (displaying the name.) When you select a row, the Master tableview controller takes the specific Contact object associated with the selected row and then passes it to the Detail view controller which then populates the Detail view using data taking from the properties of the passed Contact object.
So, that entire code block where the error occurs is unnecessary.
However, the immediate error in this code is that you are releasing an object you didn't create. In this line:
NSArray *objects = [context executeFetchRequest:request error:&error];
... you are not creating a NSArray instance with a init, new or create method. Instead, you are merely receiving an autoreleased NSArray instance created and returned by the context NSManagedObjectContext instance. When you release an object you did not create here:
[objects release];
... you cause the crash.
Conversely, you do create a NSFetchRequest here:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
... because you used init so you do have to balance that with:
[request relwase];
BTW, this type of code should not be put in viewDidLoad as the method is only called when the view is read in the first time from the nib file on disk. That is only guaranteed to happen once as the view may remain in memory when the user switches to another view. Instead, put code that needs to run each time the view appears in viewWillAppear.

Saving Core Data From Multiple TableVIews [duplicate]

This question already has answers here:
Querying Core Data with Predicates - iPhone
(4 answers)
Closed 2 years ago.
I have an app that has multiple tableviews and I want to use Core Data to capture all the data. I have two entities - freezers and items. In the first tableview I add a freezer and it saves correctly. I quit the app, re-open, and it is there. I click on the freezer (opening another tableview) and add some items and I can see them in my new sectioned tableview. I quit my app, restart it, see the freezer, click on it and there are no items.
I have my managedObjectContext in my appDelegate and reference it from there using all views, so I am not creating multiple instances. Here is the code I use to save the items to a freezer, both the managedObjectContext and my itemsArray:
Item *item = (Item *)[NSEntityDescription insertNewObjectForEntityForName:#"Item" inManagedObjectContext:[delegate managedObjectContext]];
[item setFreezer:freezerName];
[item setName:name];
[item setQuantity:quantity];
[item setSection:section];
[item setAdded:added];
[item setNotes:notes];
NSError *error = nil;
if (![[delegate managedObjectContext] save:&error]) {
NSLog(#"Freezer info didn't save. Need to handle this.");
}
[items insertObject:item atIndex:0];
Here is the code I use in the ItemViewController to retrieve the items within viewDidLoad:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"freezer == '%#'", freezerName];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Item" inManagedObjectContext:[delegate managedObjectContext]];
NSSortDescriptor *sorts = [[NSSortDescriptor alloc] initWithKey:#"section" ascending:NO];
NSArray *sort = [[NSArray alloc] initWithObjects:sorts, nil];
[request setSortDescriptors:sort];
[request setEntity:entity];
[request setPredicate:predicate];
NSError *error = nil;
NSMutableArray *results = [[[delegate managedObjectContext] executeFetchRequest:request error:&error] mutableCopy];
if(results == nil) {
NSLog(#"Error fetching results... need to handle");
}
[self setItems:results];
NSLog(#"items count:%d", [items count]);
The item count returned is zero.
I am completely stumped and have spent several hours searching online, trying different things, and I can't figure it out. I know there are some much smarter coders out there and I hope one of you can see what the problem is.
I would try to change the predicate to
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"freezer like %#", freezerName];
Hope that helps!
Maybe the problem is that you load data in
- viewDidLoad:
method. It's called only once when your view is loaded, so when underlaying data get's changed, your view controller is not aware about it.
You can either move your loading code to
- viewWillAppear:
method or introduce notifications to spread the information that data store has changed its state and reload table views upon that event.
The best way is probably to use NSFetchedResultsController as your data source, as its always aware of its data store changes. Check docs for reference to that class.

NSFetchResultsController w/ NSPredicate (relationship) vs. Basic NSFetchRequest (Pic Included)

Here is an image of the relationship I am debating:
I have a UIScrollView setup as a horizontal scroller that scrolls between 3 different UIViewControllers (containing a UITableView of course and the required delegate methods, etc.)
Each ViewController in the UIScrollView loads a UITableView of a specific MyObjectType.
(E.g. ViewController1 loads a tableview of all MyObjects where its type == MyObjectType.name)
Does this make sense? You'll notice I've setup an inverse relationship between the objects. A MyObjectType can have many MyObject's but a MyObject can only have a single MyObjectType associated to it.
When I first load one of the UIScrollView viewController's I need to determine what MyObjectType this UITableView is for. I have this working fine and I set the Table Header accordingly.
E.g. [type valueForKey:#"name"] where type is a fetched result NSManagedObject of MyObjectType.
The thing is I'm wondering, when I obtain this NSManagedObject of MyObjectType do I not also have access to a NSSet *array (ie. [type valueForKey:#"objects"]) which I can use as the UITableView's datasource? Would this work if after I add or delete an object I save the managedContext and then I always [tableView reloadData] ?
I'm guessing this would work, as long as I don't require the UITableView content to change and update dynamically as new MyObject of this type are added? For this we require a NSFetchedResultsController right?
Here is my code for loading ALL MyObject's into a UITableView (which works):
- (NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"MyObject" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sort = [[NSSortDescriptor alloc]
initWithKey:#"creationDate" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *theFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:managedObjectContext sectionNameKeyPath:#"transientSectionDate"
cacheName:#"Root"];
self.fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;
[sort release];
[fetchRequest release];
[theFetchedResultsController release];
return _fetchedResultsController;
}
Could someone PLEASE be as so kind to show my what actual NSPredicate declaration I need to correctly load ONLY MyObject's whose MyObjectType.name == #"XXXXXX"? Let's assume I already have a MyObjectType.name stored in a retained NSString inside the ViewController.
Thanks in advance!
The predicate format string would be:
#"ALL type.name=%#", typeName
However, since you do have a particular MyObjectType object, you already have direct access to the needed MyObject objects and don't have to waste time trying to fetch them. Just convert the set into a sorted array.
To keep apprised of ongoing changes while the table is active, implement observeValueForKeyPath:ofObject:change:context: in the tableview datasource object. Then send addObserver:forKeyPath:options:context: to that particular MyObjectType object like so:
[anObjectType addObserver:self
forKeyPath:#"objects"
options:(NSKeyValueObservingOptionNew |NSKeyValueObservingOptionOld)
context:nil];
Now, whenever the objects value of that paticular MyObjectType changes, the tableview's datasource will be notified and can change the table.
See Key-Value Observing Programming Guide for details.

How do I get Attributes from Core Data into an Array for - iPhone SDK

I'm trying to retrieve data from Core Data and put it into a Mutable Array
I have an Entity called 'Stock' and in Properties, attributes called : code, price & description...
How do I get the data stored in these attributes into a simple Mutable Array?
I've added this code...
NSMutableArray *array = [[NSMutableArray alloc]init];
[array addObject:[stock valueForKey:#"code"]];
and I get this error...
'-[NSCFArray insertObject:atIndex:]: attempt to insert nil'
I have a 'Managed Object Class' called 'Stock' and declared called stock. Am I missing something?
If I do this in the -cellForRowAtIndexPath...
Stock *stock1 = [fetchedResultsController objectAtIndexPath:indexPath];
array = [[NSMutableArray alloc] init];
[array addObject:stock1.code];
NSLog(#"Filtered List is? %#", array);
In the console I can see these 2 items
'The Filtered array is 810005'
'The Filtered array is 810007
'
What must I do to get these items(810005 & 810007) into an array set up in the -viewDidLoad method? Like it does in the -cellForRowAtIndexPath?
Update
Hi Marcus,
Finally got it working (well, 80%)
I put this in the -cellForRowAtIndexPath
Stock *product = nil;
if (tableView == self.searchDisplayController.searchResultsTableView)
{
filteredListContent = [NSMutableArray arrayWithObjects:stock1.code, nil];
product = [self.filteredListContent objectAtIndex:indexPath.row];
[self configureFilteredCell:cell atIndexPath:indexPath];
[filteredListContent objectAtIndex:indexPath.row];
NSLog(#"Filtered List Array List is? %#", stock1.code);
}
else
{
listContent = [NSMutableArray arrayWithObjects:stock1.code, nil];
[self configureCell:cell atIndexPath:indexPath];
NSLog(#"List Array List is? %#", stock1.code);
}
Then I used this code in the scope
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
self.savedSearchTerm = searchText;
if (searchText !=nil)
{
NSPredicate *predicate =[NSPredicate predicateWithFormat:#"code beginsWith[cd] %#", searchText];
[fetchedResultsController.fetchRequest setPredicate:predicate];
}
else
{
NSPredicate *predicate =[NSPredicate predicateWithFormat:#"code contains[cd] %#", searchText];
[fetchedResultsController.fetchRequest setPredicate:predicate];
[self.tableView reloadData];
}
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error])
{
// Handle error
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1); // Fail
}
[self.tableView reloadData];
Everything is filtering fine but when I hit cancel on the search, it's not reloading the original data...
I won't be defeated...!!
Thanx
Since you are having this issue in your -viewDidLoad, I am guessing (and without the code from -viewDidLoad, it is only a guess) that you are trying to fetch objects from the NSFetchedResultsController before the -executeFetch: has been called on the controller and therefore you are in the land of nils.
I would suggest setting a break point in your -viewDidLoad and watching the values and you walk through your code. This will tell you what is nil and where.
Of course a better question is, why are you trying to put NSManagedObject instances into a NSMutableArray? Since they are already in your NSFetchedResultsController is there really a need to build up another array? What is the end goal?
Update
Now I understand what you are trying to do.
Solution 1
Only populate the array when a search has been conducted. Take a look at the http://developer.apple.com/iphone/library/samplecode/TableSearch/index.html example code and you should see how to apply it to your situation.
If you want to enter the table view with a pre-defined search then you need to perform it after you have executed a -performFetch: in the NSFetchedResultsController.
Solution 2
Modify the NSPredicate on the NSFetchedResultsController to include your search terms and then execute -performFetch: on the NSFetchedResultsController, you may have to do a -reloadData on the table as well, I am not sure.
When the user clears the search field you reset the predicate and re-fetch everything. Since it is all cached there should be no performance penalty.
Solution 2 just occurred to me and I have not tested it personally but there is no reason it shouldn't work just fine. Should even give you live updates within the search.
Have you read the documentation? You fetch your Stock instances (all of them or filter them with a predicate), then do with them whatever you please.
You can then add their properties to an array individually:
[array addObject:[stockInstance valueForKey:#"price"];
... or use a combination of < NSKeyValueCoding > protocol methods such as -dictionaryWithValuesForKeys: NSDictionary methods such as -objectsForKeys:notFoundMarker: to get an array for given keys.
This may or may not actually be what you need to do, though. It depends on what you intend to use the resulting array for. If you want a quick sum of all matching Stock instances' "price" values, for example, you can use Set and Array Operators. It really depends on what you're trying to achieve.
When I got your error,
'-[NSCFArray insertObject:atIndex:]: attempt to insert nil'
I had given the fetchedRequest a sort descriptor that had a nil key. The error appeared when I used these lines:
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
The error disappeared when I set the key to #"name":
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];