ebook img

Core Data - objc.io PDF

271 Pages·2016·2.573 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Core Data - objc.io

Version2.0(December2016) ©2016Kugler,EggertundEidhofGbR AllRightsReserved Formorebooksandarticlesvisitusathttp://objc.io Email:[email protected] Twitter:@objcio Introduction HowThisBookApproachesCoreData 9 ANoteonSwift 11 Part1 CoreDataBasics 1 HelloCoreData CoreDataArchitecture 16 DataModeling 17 SettingUptheStack 20 ShowingtheData 22 ManipulatingData 30 Summary 36 NotesforPre-iOS10/macOS10.12 37 2 Relationships AddingMoreEntities 40 Subentities 43 CreatingRelationships 46 OtherTypesofRelationships 48 EstablishingRelationships 50 RelationshipsandDeletion 54 AdaptingtheUserInterface 57 Summary 59 3 DataTypes StandardDataTypes 61 PrimitivePropertiesandTransientAttributes 63 CustomDataTypes 64 DefaultValuesandOptionalValues 71 Summary 72 Part2 UnderstandingCoreData 4 AccessingData FetchRequests 76 Relationships 85 OtherWaystoRetrieveManagedObjects 86 MemoryConsiderations 87 Summary 89 5 ChangingandSavingData ChangeTracking 92 SavingChanges 94 BatchUpdates 99 Summary 101 6 Performance PerformanceCharacteristicsoftheCoreDataStack 104 AvoidingFetchRequests 108 OptimizingFetchRequests 116 InsertingandChangingObjects 123 HowtoBuildEfficientDataModels 124 StringsandText 128 EsotericTunables 128 Summary 128 Part3 ConcurrencyandSyncing 7 SyncingwithaNetworkService OrganizationandSetup 131 SyncingArchitecture 133 ContextOwner 134 ReactingtoLocalChanges 137 ReactingtoRemoteChanges 141 ChangeProcessors 142 DeletingLocalObjects 145 GroupsandSavingChanges 146 ExpandingtheSyncArchitecture 147 8 WorkingwithMultipleContexts ConcurrencyRules 152 MergingChanges 158 TheDefaultConcurrentSetup 159 SetupswithMultipleCoordinators 161 SetupswithNestedContexts 163 ComplexityofNestedContexts 167 Summary 172 9 ProblemswithMultipleContexts SaveConflictsandMergePolicies 175 QueryGenerations 181 DeletingObjects 183 UniquenessConstraints 187 Summary 189 Part4 AdvancedTopics 10 Predicates SimplePredicates 193 CreatingPredicatesinCode 195 FormatStrings 195 CombiningPredicates 199 TraversingRelationships 201 MatchingObjectsandObjectIDs 203 MatchingStrings 204 TransformableValues 206 PerformanceandOrderingExpressions 207 Summary 208 11 Text TheComplexityofUnicode 210 Searching 211 Sorting 215 Summary 220 12 ModelVersionsandMigratingData ModelVersions 222 TheMigrationProcess 225 InferredMappingModels 234 CustomMappingModels 235 MigrationandtheUI 240 TestingMigrations 241 Summary 243 13 Pro(cid:297)ling SQLDebugOutput 245 CoreDataInstruments 252 ThreadingGuard 256 Summary 256 14 RelationalDatabaseBasicsandSQL AnEmbeddedDatabase 259 Tables,Columns,andRows 260 ArchitectureoftheDatabaseSystem 261 TheDatabaseLanguageSQL 264 Relationships 266 Transactions 269 Indexes 269 Journaling 270 Summary 271 Introduction CoreDataisApple’sobjectgraphmanagementandpersistencyframeworkforiOS, macOS,watchOS,andtvOS.Ifyourappneedstopersiststructureddata,CoreDataisthe obvioussolutiontolookinto:it’salreadythere,it’sactivelymaintainedbyApple,andit hasbeenaroundformorethan10years.It’samature,battle-testedcodebase. Nevertheless,CoreDatacanalsobesomewhatconfusingatfirst;it’sflexible,butit’snot obvioushowtobestuseitsAPI.Thatsaid,thegoalofthisbookistohelpyougetofftoa flyingstart.Wewanttoprovideyouwithasetofbestpractices—rangingfromsimpleto advancedusecases—sothatyoucantakeadvantageofCoreData’scapabilitieswithout gettinglostinunnecessarycomplexities. Forexample,CoreDataisoftenblamedforbeingdifficulttouseinamultithreaded environment.ButCoreDatahasaveryclearandconsistentconcurrencymodel.Used correctly,ithelpsyouavoidmanyofthepitfallsinherenttoconcurrentprogramming. Theremainingcomplexitiesaren’tspecifictoCoreDatabutrathertoconcurrencyitself. Wegointothoseissuesinthechapteraboutproblemsthatcanoccurwithmultiple contexts,andinanotherchapter,weshowapracticalexampleofabackgroundsyncing solution. Similarly,CoreDataoftenhasthereputationofbeingslow.Ifyoutrytouseitlikea relationaldatabase,you’llfindthatithasahighperformanceoverheadcomparedto,for example,usingSQLitedirectly.However,whenusingCoreDatacorrectly–treatingitas anobjectgraphmanagementsystem–thereareactuallyquiteafewplaceswhereitends upbeingfasterduetoitsbuilt-incachesandobjectmanagement.Furthermore,the higher-levelAPIletsyoufocusonoptimizingtheperformance-criticalpartsofyour applicationinsteadofreimplementingpersistencyfromscratch.Throughoutthisbook, we’llalsodescribebestpracticestokeepCoreDataperformant.We’lltakealookathow toapproachperformanceissuesinthededicatedchapteraboutperformance,aswellas intheprofilingchapter. How This Book Approaches Core Data ThisbookshowshowtouseCoreDatawithworkingexamples—it’snotanextended APImanual.Wedeliberatelyfocusonbestpracticeswithinthecontextofcomplete examples.Wedosobecause,inourexperience,stringingallthepartsofCoreData togethercorrectlyiswheremostchallengesoccur. Inaddition,thisbookprovidesanin-depthexplanationofCoreData’sinnerworkings. Understandingthisflexibleframeworkhelpsyoumaketherightdecisionsand,atthe sametime,keepyourcodesimpleandapproachable.Thisisparticularlytruewhenit comestoconcurrencyandperformance. SampleCode YoucangetthecompletesourcecodeforanexampleapponGitHub.We’reusingthis appinmanypartsofthebooktoshowproblemsandsolutionsinthecontextofalarger project.We’veincludedthesampleprojectinseveralstagessothatthecodeonGitHub matchesupwiththecodesnippetsinthebookasbestaspossible. Structure Inthefirstpartofthebook,we’llstartbuildingasimpleversionofourappto demonstratethebasicprinciplesofhowCoreDataworksandhowyoushoulduseit. Eveniftheearlyexamplessoundtrivialtoyou,westillrecommendyougooverthese sectionsofthebook,asthelater,morecomplexexamplesbuildontopofthebest practicesandtechniquesintroducedearlyon.Furthermore,wewanttoshowyouthat CoreDatacanbeextremelyusefulforsimpleusecasesaswell. Thesecondpartfocusesonanin-depthunderstandingofhowallthepartsofCoreData playtogether.We’lllookindetailatwhathappenswhenyouaccessdatainvariousways, aswellaswhatoccurswhenyouinsertormanipulatedata.Wecovermuchmorethan what’snecessarytowriteasimpleCoreDataapplication,butthisknowledgecancome inhandyonceyou’redealingwithlargerormorecomplexsetups.Buildingonthis foundation,weconcludethispartwithachapteraboutperformanceconsiderations. Thethirdpartstartswithdescribingageneralpurposesyncingarchitecturetokeepyour localdatauptodatewithanetworkservice.Thenwegointothedetailsofhowyoucan useCoreDatawithmultiplemanagedobjectcontextsatonce.Wepresentdifferent optionstosetuptheCoreDatastackanddiscusstheiradvantagesanddisadvantages. Thelastchapterinthispartdescribeshowtonavigatetheadditionalcomplexityof workingwithmultiplecontextsconcurrently. Thefourthpartdealswithadvancedtopicslikeadvancedpredicates,searchingand sortingtext,howtomigrateyourdatabetweendifferentmodelversions,andtoolsand techniquestoprofiletheperformanceofyourCoreDatastack.Italsoincludesachapter thatintroducesthebasicsofrelationaldatabasesandtheSQLquerylanguagefromthe perspectiveofCoreData.Ifyou’renotfamiliarwiththese,itcanbehelpfultogothrough

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.