MOBILE

iPhone Developer : Search Tables and Core Data

9/18/2012 1:14:59 AM
Core Data stores are designed to work efficiently with NSPredicates. Predicates allow you to create fetch requests that select only those managed objects that match the predicate’s rule or rules. Adding a predicate to a fetch request limits the fetched results to matching objects.

This recipe uses a search bar to select data from the persistent store, displaying the results in a table’s search sheet. Figure 19-2 shows a search in progress.

Figure 1. To power this search table with Core Data, the fetched results must update each time the text in the search box changes.


As the text in the search bar at the top of the table changes, the search bar’s delegate receives a searchBar:textDidChange: callback. In turn, that method performs a new fetch. 

The recipe’s performFetch method creates that simple predicate based on the text in the search bar. It sets the request’s predicate property to limit matches to names that contain the text, using a case insensitive match. contains matches text anywhere in a string. The [cd] after contains refers to case and diacritic insensitive matching. Diacritics are small marks that accompany a letter, such as the dots of an umlaut or the tilde above a Spanish n.

For more complex queries, assign a compound predicate. Compound predicates allow you to combine simple predicates together using standard logical operations like AND, OR, and NOT. Use the NSCompoundPredicate class to build a compound predicate out of a series of component predicates, or include the AND, OR, and NOT notation directly in NSPredicate text.

All the cell and section methods are tied to the results object and its properties, simplifying implementation even when adding these search table features.

Recipe 1. Using Fetch Requests with Predicates
- (void) performFetch
{
    // Init a fetch request
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
        entityForName:@"Crayon" inManagedObjectContext:self.context];
    [fetchRequest setEntity:entity];

    // Apply an ascending sort for the color items
    NSSortDescriptor *sortDescriptor =
        [[NSSortDescriptor alloc] initWithKey:@"name"
        ascending:YES selector:nil];
    NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor];
    [fetchRequest setSortDescriptors:descriptors];

    // Recover query
    NSString *query = self.searchBar.text;
    if (query && query.length) fetchRequest.predicate =
        [NSPredicate predicateWithFormat:@"name contains[cd] %@",
        query];

    // Init the fetched results controller
    NSError *error;
    self.fetchedResultsController =
        [[NSFetchedResultsController alloc]
            initWithFetchRequest:fetchRequest
            managedObjectContext:self.context
            sectionNameKeyPath:@"section" cacheName:@"Root"];
    self.fetchedResultsController.delegate = self;
    [self.fetchedResultsController release];
    if (![[self fetchedResultsController] performFetch:&error])
        NSLog(@"Error %@", [error localizedDescription]);

    [fetchRequest release];
    [sortDescriptor release];
}					  


Other  
  •  iPhone Developer : Using Core Data for a Table Data Source
  •  Anita Mai Tan - The Container Is Worth More Than The Contents
  •  No New Toaster – Refrigerators
  •  The State Of Mobile... Creative Media In 2012 (Part 2)
  •  The State Of Mobile... Creative Media In 2012 (Part 1)
  •  A Not So New Competitor
  •  BlackBerry Java Application : installing the Java Development Kit (JDK), downloading Eclipse with the JDE plugin
  •  BlackBerry Java Application : Installing the Development Environment - downloading the Java Development Kit
  •  iOS 6 Playing It Safe (Part 1)
  •  iOS 6 Playing It Safe (Part 2)
  •  Planet Of The Apps – Travel (Part 1)
  •  Planet Of The Apps – Travel (Part 2)
  •  Planet Of The Apps – Travel (Part 3)
  •  Top 10 Smartphones August – September (Part 1) - Samsung Galaxy S III, HTC One X, Apple iPhone 4S,Nokia Lumia 800,Sony Xperia S
  •  Top 10 Smartphones August – September (Part 2) - Huawei Ascend P1, HTC Radar, Samsung Galaxy Note,BlackBerry Bold 9900
  •  Got Yourself A Fancy New Nexus Flexus
  •  Nokia 808 Pureview - Best For Convergists
  •  Tough Phones : Work or play in harsh environments
  •  Take Your Office On The Go
  •  Tablets For All Budgets (Part 3) - Apple New iPad, Asus Transformer Infinity TF700
  •  
    Top 10
    Nikon 1 J2 With Stylish Design And Dependable Image And Video Quality
    Canon Powershot D20 - Super-Durable Waterproof Camera
    Fujifilm Finepix F800EXR – Another Excellent EXR
    Sony NEX-6 – The Best Compact Camera
    Teufel Cubycon 2 – An Excellent All-In-One For Films
    Dell S2740L - A Beautifully Crafted 27-inch IPS Monitor
    Philips 55PFL6007T With Fantastic Picture Quality
    Philips Gioco 278G4 – An Excellent 27-inch Screen
    Sony VPL-HW50ES – Sony’s Best Home Cinema Projector
    Windows Vista : Installing and Running Applications - Launching Applications
    Most View
    Top 10 Cameras - Jan 2013
    Silverlight Recipes : Using Sockets to Communicate over TCP (part 4) - The Chat Server
    Windows Vista : Make Your Hardware Perform (part 2) - Maximize the Windows Performance Rating
    Canon i-Sensys LBP7680Cx
    Expert Computing Advice – January 2013 (Part 2)
    .NET Debugging : PowerDbg (part 1) - Installing PowerDbg & Analyze-PowerDbgThreads
    HP Unveils Glass Design HP ENVY Spectre
    Droid Support - Get Your Settings Under Control (Part 2)
    DSLs in Boo : Implementing the Scheduling DSL
    iPhone 3D Programming : Adding Depth and Realism - Creating and Using the Depth Buffer
    Archos 101XS - A Decent Package At A Fair Price
    Application Patterns and Tips : Deploy Applications Using ClickOnce
    Windows 7 : Maintaining Your System Configuration (part 3) - Configuring User Profiles, Environment Variables, and Startup and Recovery
    iPad 4 - The Fastest iPad Until Now
    Discover Great & Low-Cost Mac Products – November 2012
    Samsung HMX-H304
    PhotoDirector 3 - Gets snap happy
    Windows Phone 7 Development : Building a Phone Client to Access a Cloud Service (part 4) - Coding NotepadViewModel
    Legal Trouble with Social Networks (Part 2) - How to avoid unnecessary legal trouble
    Programming with DirectX : Shading and Surfaces - Implementing Texture Mapping (part 2) - Multi Texture Demo