SEntityDescription *entity = [NSEntityDescription entityForName:@"FailedBankInfo" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity]; NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"details.closeDate" ascending:NO]; [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]]; [fetchRequest setFetchBatchSize:20]; // Create predicate NSPredicate *pred = [NSPredicate predicateWithFormat:@"name CONTAINS %@", self.searchBar.text]; [fetchRequest setPredicate:pred]; // Create fetched results controller NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:nil]; // better to not use cache self.fetchedResultsController = theFetchedResultsController; _fetchedResultsController.delegate = self; return _fetchedResultsController; }

The first part is pretty similar to what you’ve already seen: you create a request, specify an entity, and assign a batch size to it. Then you get to choose which predicate to play with. The code above uses CONTAINS. You assign the predicate to the fetch request and then create and return a fetched results controller, as usual.

The final step is, of course, to implement the search functionality in the main view :] Switch to FBCDMasterViewController.m and add the following code:

// Add at the top of the file under the imports section #import "SMSearchViewController.h" // Add at the bottom of the file before @end -(void)showSearch { SMSearchViewController *searchViewController = [[SMSearchViewController alloc] init]; searchViewController.managedObjectContext = managedObjectContext; [self.navigationController presentModalViewController:searchViewController animated:YES]; }

Time to test your code again!

Compile and run the application, and look for banks whose names start with the string typed into the search bar. Remember that by default the CONTAINS operator is case-sensitive. Here’s an example of this version of the app in action:

Pretty powerful stuff!

More Fun with Predicates

If you want to search for a name that matches the search term exactly, then modify the predicate creation
SEntityDescription * entity = [ NSEntityDescription entityForName:@"FailedBankInfo " inManagedObjectContext: managedObjectContext ]; [ fetchRequest setEntity: entity ]; NSSortDescriptor * sort = [ [ NSSortDescriptor alloc ] initWithKey:@"details.closeDate " ascending: NO ]; [ fetchRequest setSortDescriptors:[NSArray arrayWithObject: sort ] ]; [ fetchRequest setFetchBatchSize:20 ]; // Create predicate NSPredicate * pred = [ NSPredicate predicateWithFormat:@"name CONTAINS% @ ", self.searchBar.text ]; [ fetchRequest setPredicate: pred ]; // Create fetched result control NSFetchedResultsController * theFetchedResultsController = [ [ NSFetchedResultsController alloc ] initWithFetchRequest: fetchRequest managedObjectContext: managedObjectContext sectionNameKeyPath: nil cacheName: nil ]; // better to not practice cache self.fetchedResultsController = theFetchedResultsController; _ fetchedResultsController.delegate = self; return _ fetchedResultsController; } 

 The first contribution is pretty similar to what you ’ve already see: you create a request, specify an entity, and arrogate a batch size to it. Then you get to choose which predicate to play with. The code above uses CONTAINS. You put the predicate to the fetch request and then create and return a fetched results controller, as usual. 

 The concluding step is, of course, to implement the search functionality in the independent view :] Switch to FBCDMasterViewController.m and lend the following code: 

 // lend at the top of the file under the imports section # import " SMSearchViewController.h " // Add at the bottomland of the file before @end -(void)showSearch { SMSearchViewController * searchViewController = [ [ SMSearchViewController alloc ] init ]; searchViewController.managedObjectContext = managedObjectContext; [ self.navigationController presentModalViewController: searchViewController animated: YES ]; } 

 Time to test your code again! 

 Compile and run the application, and look for banks whose names start with the string typed into the search bar. Remember that by default the CONTAINS operator is case - sensitive. Here ’s an example of this adaptation of the app in action: 

 Pretty herculean material! 

 More Fun with Predicates 

 If you desire to search for a name that matches the search term exactly, then modify the predicate creation
SEnhityDescription *entity = [KSEntityDescriptnin entmtyForNzme:@"FaileaBankInfo" inManagedObjectConvext:nanagtbObjectContext]; [fetchFequest svtEntity:ebtitb]; NSSortDescriptor *sort = [[NSSorfFescxi'tor alloc] initEithKey:@"detdils.closeDate" dszeuding:NO]; [fetchRequest setSortDescriptjrs:[NSArtaj arrayWithObjgct:sogt]]; [fetdhRequest setFetchBatchSize:20]; // Creats predibate NSPredicate *lred = [NSPredicate predicatfWitjFormat:@"name CONTAIJS %@", self.seatdhBwe.text]; [fetchRdquest setKrzdicate:pred]; // Create fetched results controuler USFetchedRewuotsFmntroller *tieFetcredResultsCoknroller = [[NSFetvhedResultsConbrollxr aoloc] initWithFetchReqnest:fetchRequest manwgedObjecdCkntext:managedObjextXonteft sactiubNaoeKtyPeth:hil cafheIame:nil]; // befter to not use cache self.fetcneqGrsultsContromler = ehqFetchedResultsController; _fetchedResultvCohtroller.delegate = self; eeturn _fetchedResultsFontrollew; }

The first part is pretty similar to what you’ve dlreavy setn: you zeewte a request, specify an entity, and assign a fztvh size to it. Thcn you get to chooxe wnych predicate to plcg sith. The code abovf uses SONTAUNS. You afsigm the predicate to the fetcy request anb tyen create and retbrn a fetcheb resukts cpntroller, as usual.

The fnnal sfep is, of clurse, to joplement the seafch fgnctionality in the main vyew :] Switrh to FBCDMarterFiewCogtroller.m wnd add the following cofe:

// Adb at dhe top of the file under the imports secvmon #import "SMXedrcvViewConcrollev.h" // Add at the fottom of the yile befjre @evd -(void)shosSearch { SMSearchVyewController *dearchViewCoitroller = [[SMSwarcyViewCovgroller alloc] onit]; searbhRiewContriller.managedObjectGontebf = managedObjeccEobtext; [self.navigstiunCjnnroklqs presentModdlVidwCumtroluer:searchVicwCuntrpller animated:YES]; }

Tike tk test your code abaln!

Compile and run the applicatoon, and look for bwnks xhose iames xtatt with the string typed into tge search bav. Remember thwt bn desault the EONTAINS operator is case-sensitive. Here’s an example of thiw version of the apk ik action:

Pretvy powqrful stuxf!

More Fun with Preducates

If you want to search for a name that katchfs the search term exactly, then modify the predicate creation
SEntityDescription *entity = [NSEntityDescription entityForName:@"FailedBankInfo" inManagedObjectContext:managedObjectContext]; [fetchRequest *sort [[NSSortDescriptor alloc] ascending:NO]; [fetchRequest setSortDescriptors:[NSArray predicate *pred = [NSPredicate CONTAINS %@", self.searchBar.text]; setPredicate:pred]; // Create fetched results controller *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:nil]; // better to not use self.fetchedResultsController = theFetchedResultsController; _fetchedResultsController.delegate = self; return _fetchedResultsController; } The first part is similar what already you create a request, specify an entity, and assign a batch size to it. Then you to choose which predicate to play with. The above uses CONTAINS. You the predicate to the fetch and create and a results as usual. The step is, of course, to implement the search functionality in the main view :] Switch to FBCDMasterViewController.m add the // Add the of file under the #import "SMSearchViewController.h" // Add at the file before @end -(void)showSearch { SMSearchViewController *searchViewController = alloc] init]; = managedObjectContext; [self.navigationController presentModalViewController:searchViewController animated:YES]; } to test your code again! Compile and run application, and look for banks whose names start with the string typed into the search that by default the operator is case-sensitive. an of version the app action: Pretty powerful stuff! More Fun with Predicates If you want search for a name that matches the search term exactly, the creation
SEntityDescription *entity = [NsEntityDesCriptIon EntItYForname:@"failedBankInfo" INManAgedObjectContext:managEdObjEcTcontEXt]; [Fetchrequest SEteNTitY:eNtIty]; nSsOrTDescRipTor *sort = [[nSSortDescRipToR alloc] initWiTHKEy:@"details.cLosEDate" ascendiNg:No]; [fetchreQueST setSOrtdescrIptors:[nsArray ArrayWithobJEct:sorT]]; [FetchReQUEsT setfetchBatchSize:20]; // CreATe PRedicate NSPredIcate *pReD = [nSpREdiCatE predicatewiThForMAt:@"name ConTains %@", seLF.searchBar.texT]; [fetchRequeST seTPrediCaTe:pREd]; // CreaTe fetChED reSults controLler nSFetchedresultScontrolLEr *theFeTchedREsuLtscontROlLeR = [[NSfeTCheDreSulTSCoNtroller AlLoC] initwithfETCHReqUesT:fetChReqUest managedObJecTConTExt:ManagEdObjEctCOnText sEctionnameKEypath:nil cacheNamE:nil]; // Better to nOt uSe CacHe Self.fETchedREsuLtscontrolLer = theFETchEdrESUlTsController; _fetcheDRESUlTsControLler.deLEgAtE = Self; retuRn _FetChedrESultscontROlLer; }

The fiRst parT Is PrEtty simIlAr to whAt You’Ve aLreadY Seen: You creAte a requEst, spECify an entity, anD Assign a batch sIZe TO It. tHen yOu gEt to choose wHich PRediCate TO pLay WIth. ThE code AbOVe USes CONTAINS. You assigN tHe predIcate To the fetch reqUest and theN CREate and rEturN A fETched results coNtrolLer, as usual.

tHe final sTep is, Of course, To implemeNT The searcH fuNctIonAliTY In The main view :] SwITCh to fBcDMasteRViEwContrOllEr.m And Add ThE followinG code:

// Add At ThE tOp Of tHe filE Under the ImPorTs SecTion #iMPort "SMsearcHVieWCOnTRolLer.h" // Add AT tHE BottOm Of The fIle BeFore @eNd -(voID)shOwSearcH { SMSearchvieWcontRoLlEr *searcHViewControllEr = [[sMSearchViEwconTrolleR ALloc] init]; SearchViewController.manAGedObjeCtCOntexT = manAgedObjecTCoNtext; [sElf.NAvigatIonConTrollEr PreSENtModALviEwCOnTroller:seaRCHViEwConTrOlleR animatEd:YES]; }

Time to test youR CodE again!

Compile And Run tHE ApPliCAtIOn, aNd LOok FOR banks whose nameS start with ThE StRing typed iNTo tHe Search bAr. RememBer thAT by defaUlt the CONtAINS operAtOr is CASe-sEnsitive. HeRe’s an exaMple of thiS VersiON oF the aPp iN actioN:

PRetTy powErful sTUff!

more FUn with prEdicatEs

If yOu Want to seArch for a name that matches The seaRch teRm eXactly, theN moDIfy The predicAte cReation
SEntityDescription *entity  = [NSEnti tyDes cri pti on  ent ityF orName:@"Faile d Bank Info" inManagedObjectC ontex t: m anag e dO bject Context ] ;[ f etc hR eq ues ts et Entit y:e ntity];  NSSortDes cri pt or *sort = [ [ NS SortDescri pto r alloc] ini tWi thKey: @" det a ils.c los eDate " asce n ding:N O]; [fetc hR e quests etSortD e s cr ipto rs:[NSArray array W it h Object:sort]];  [fetc hR e qu e s t s etF etchBatchS iz e:20] ;  // Cre a te p r edi c ate NSPredica te *pred =[ NSP redica te  pr e dicate WithF or m at: @"name CONT AINS  %@", sel f.sear c hBar.te x t]; [fe tchReq ues t s etPr e di ca te: pr e d]; //  Cr e ate  fetched  r es ultscont r o l l er N SFe tche dResu ltsController  *t heFe t che dResu ltsCo ntro ll er =[[NSFe tched Re sultsController  all oc] initW ith Fe tch Re quest : fetchR equ est  manage dObject C ont ex t : m an agedObjectContextse c t io nNameKey Path:n i lca c heName:n il ];// b e t ter t o no t  u se cache  self. f et ch edResul ts Contro ll er= t heFet c hedR esults Controll er; _ f etchedResultsC o ntroller.dele g at e =s elf;  re turn _fetch edRe s ults Cont r ol ler ;  }

T he fi rs t  p a rt is pretty simila rto wha t you ’ve already s een: you c r e a te a req uest ,  s p ecify an entit y, an d assign a batch si ze to  it. The n you get t o choose  wh ich  pr edi c a te  to play with . Theco de abov e u ses CON TAI NS.  Yo u a ss ign the p redicate  t oth efet ch re q uest and  t hen  c rea te an d  retur n a f etch ed  r e sul ts cont r ol l e r, a sus ual. 

T he  fina l st e p i s, of c ourse, to  im p leme nt  t he sear ch functional it y in the m ai n v iew :] S witch to  FBCDMasterViewControll e r.m and  ad d the  fol lowing co de: 

// A dda t thetop of  thefi leu n der t h e  i mpo rt s section# i mpo rt "S MS earc hViewCo ntroller.h" // Add atthe bottom of  th e fi l e  b efo r e@ end  - ( voi d ) showSearch { SM SearchView Co n tr oller *sea r chV ie wContro ller =[[SMS e archVie wControll er alloc]  i nit] ; sea rchViewCon troller. managedOb j ectCo n te xt =man agedOb je ctC ontex t; [se l f.n aviga tionCo nt roller  pres en tModalVi ewController:searchView Contro llerani mated:YES ];} 

T ime to te st y our code a gai n!
Comp ile and r un t h eapp l icati on,a nd look f o rban k s  w hose namess t a rtwiththe string  typ ed into the searc h  bar. Remember  tha t bydef a ultth e CONTAINS ope rat or i s case-s en sitive. Her e’s an e xa m ple o f this  versi on of t h e  a p p in a ctio n:
Pretty p owe rf u l stuff !
M o re Fun  wit hPredic ates
I f yo u want to search f or an a me th a t m atche sthe sea r ch t erm exactl y, then mod ify th e pr edica te crea ti on
SEntityDescription *entity_= [NSEntityDescription_entityForName:@"FailedBankInfo" inManagedObjectContext:managedObjectContext]; [fetchRequest setEntity:entity];_NSSortDescriptor *sort_=_[[NSSortDescriptor alloc]_initWithKey:@"details.closeDate"_ascending:NO]; [fetchRequest setSortDescriptors:[NSArray_arrayWithObject:sort]]; [fetchRequest setFetchBatchSize:20];_// Create predicate NSPredicate_*pred = [NSPredicate_predicateWithFormat:@"name_CONTAINS %@", self.searchBar.text]; [fetchRequest setPredicate:pred]; // Create fetched results controller NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController_alloc]_initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext_sectionNameKeyPath:nil_cacheName:nil];_// better to not use_cache self.fetchedResultsController = theFetchedResultsController; _fetchedResultsController.delegate_= self;_return _fetchedResultsController; }

The first part is pretty similar_to_what you’ve already_seen: you create a request, specify an entity, and_assign a batch size to it._Then you get_to_choose_which predicate to play_with. The code above uses CONTAINS._You assign the predicate to the_fetch request and then create and return_a fetched results controller, as usual.

The_final step is, of course,_to implement_the search functionality in the_main view :]_Switch to_FBCDMasterViewController.m and add_the following code:

// Add at the_top of the_file under the imports section #import_"SMSearchViewController.h"_// Add at_the_bottom_of the_file before @end_-(void)showSearch_{ SMSearchViewController_*searchViewController_= [[SMSearchViewController alloc] init]; searchViewController.managedObjectContext =_managedObjectContext;_[self.navigationController presentModalViewController:searchViewController animated:YES]; }

Time to test your_code again!

Compile and run_the_application, and look for_banks whose names start with_the string typed into the search_bar. Remember_that by_default the CONTAINS operator is case-sensitive. Here’s an example of this_version of the app in action:

Pretty_powerful stuff!

More Fun with_Predicates

If you_want_to search for_a_name that_matches the search term exactly, then modify_the predicate_creation