Search code examples
iosuitableviewcore-datansfetchrequestnsfetchedresultscontroller

Core Data: Fetch


I have a 5 screens. Each screen has options the user choses i.e. via Time & Date picker, and some UIFields that the user will type in. So I created ONE Entity and added all the attributes (25). I created a NSObjectSubClass called LM

In each scene I'm doing the following:

@property (nonatomic, strong) LM *lMData;

NSString *date = [[NSString alloc] initWithFormat:@"%@", [dateFormatter stringFromDate:selectedDate]];
            DateLabel.text = date;
            self.lMData.dateLabel = date;

self.lmData.nameField5 = UITextFieldName5.text;

Before the User Segue's to the next screen, I have:

NSError *error;
NSManagedObjectContext *context = self.managedObjectContext;

 if (![context save:&error])
      {
           NSLog(@"There was an error in Save:%@",error);
      }

Now to fetch, all I want to do is show the data in a UITableViewController that is custom. That has 12 Sections and will show 2 cells in each section. I don't really need sorting. I just want the cells to show up in the right sections.

To fetch, I have the following method:

-(NSFetchedResultsController *) fetchResultsController
{
    if (_fetchResultsController !=nil)
{
    return _fetchResultsController;
}

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"LM"
                                          inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"startTimeLabel" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];

_fetchResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];

return _fetchResultsController;

}

From what I read, it appears that in order for me to fetch I have to sort, hence, the following line:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"startTimeLabel"

There is an attribute called "startTimeLabel" in my entity. But I have it in there because I'm being forced to sort. However, I really don't need to sort.

Now to display, which is not displaying anything at this point:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

  return [[self.fetchResultsController sections] count];   //I need 10 sections here;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    id<NSFetchedResultsSectionInfo> secInfo = [[self.fetchResultsController   sections]objectAtIndex:section];
    return [secInfo numberOfObjects]; //I need 2 rows in each section here
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    LM *letsMeetData = [self.fetchResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = letsMeetData.dateLabel;

    return cell;
}

Questions:

  1. Is my code to save and fetch correct?

  2. What can I do to get rid of the Sort? I don't need to Sort.

  3. I know my code to display the fetched data in the UITableView is wrong. Please advise.

  4. Last, I also need to save each of these forms as objects so the user can later pull them up later. Do I need to create another Entity to store LM objects?

Thanks


Solution

  • Hey to work with coredata you need to create an Entity class from NSManagedObject.

    (1)You can save and retrieve the data using the entity class.

    LM_Entity *lm = [NSEntityDescription insertNewObjectForEntityForName:@"LM_Entity" inManagedObjectContext:self.managedObjectContext];
    //Your code
    lm.nameField5 = UITextFieldName5.text;
    //Now save
    [self.managedObjectContext save:&error];
    

    While retrieving use

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"LM_Entity"
                                          inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    

    (2)You need to specify a sort descriptor while working with NSFetchedResultsController.

    (3)Your code is correct for displaying the fetched data

    (4) Yes you need to create an Entity class to save and retrieve the data.(see 1).

    Follow this tutorial for more information about coredata.