开发者

Loading all the values of an attribute of core data to an array

I have an attribute "term" which is a NSString in my core data "Event". When the table view is loaded I want all the values of "name" to be loaded to an array.

I used the code

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
      Event   *event  = nil;
      event = [fetchedResultsController objectAtIndexPath:indexPath];
    if(searching){
        cell.textLabel.text = [copyListOfItems objectAtIndex:indexPath.row];
    }else{   
          if(event.term){ 
                [listOfItems addObject:event.term]; 
         }
          cell.textLabel.text = event.term;
          cell.detailTextLabel.text = event.definition;
      }
}

The problem is that all the terms are not loaded to the NSMutableArray listOfItems. It is loaded when the table cel开发者_如何转开发ls is scrolled to bottom.

How to load all the contents of "term" from core data to the array listOfItems.

Any help will be greatly appreciated.


You are most likely looking at Core Data wrong. Core Data is not a database. It is an object graph that happens to persist to a database. Having said that, your question is better asked as "how can I load all instances of the entity 'Event' and access its term property".

To do that, you want to want to build and execute a NSFetchRequest against the 'Event' entity with no predicate.

NSManagedObjectContext *moc = ...;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Event" inManagedObjectContext:moc]];
NSError *error = nil;
NSArray *events = [moc executeFetchRequest:request error:&error];
NSAssert2(events != nil && error == nil, @"Error fetching events: %@\n%@", [error localizedDescription], [error userInfo]);

From here you can then use 'KVC' to retrieve an array of the name property:

NSArray *namesArray = [events valueForKey:@"name"];

Which will result in an array with just that string populated.

However the better question is, why do you want the array if you are displaying everything in a table? The NSFetchedResultsController already has all of the 'Event' entities retrieved for you; it is only the display that is bound to the table. What is your goal?

Update

Thank You very much for the detailed answer Mr Marcus... My goal is to search a particular "term" from the core data using search bar. Is there any better method for this to do?

Yes there is, and there are many solutions to the problem. You can access all of the results from the existing NSFetchedResultsController using its -fetchedObjects property. From there you can get a filtered array by applying a NSPredicate against that array using -filteredArrayUsingPredicate: and you can then use that array in your search results.

If you do a search on SO for Core Data and the UISearchDisplayController, I suspect you will turn up many results and suggestions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜