FREE ELECTRONIC LIBRARY - Books, dissertations, abstract

Pages:   || 2 |

«Core Data in Objective-C, Third Edition Data Storage and Management for iOS and OS X This PDF file contains pages extracted from Core Data in ...»

-- [ Page 1 ] --

Extracted from:

Core Data in Objective-C, Third Edition

Data Storage and Management for iOS and OS X

This PDF file contains pages extracted from Core Data in Objective-C, Third Edition,

published by the Pragmatic Bookshelf. For more information or to purchase a

paperback or PDF copy, please visit http://www.pragprog.com.

Note: This extract contains some colored text (particularly in code listing). This

is available only in online versions of the books. The printed versions are black and white. Pagination might vary between the online and printed versions; the content is otherwise identical.

Copyright © 2016 The Pragmatic Programmers, LLC.

All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher.

The Pragmatic Bookshelf Dallas, Texas • Raleigh, North Carolina Core Data in Objective-C, Third Edition Data Storage and Management for iOS and OS X Marcus S. Zarra The Pragmatic Bookshelf Dallas, Texas • Raleigh, North Carolina Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trademarks of The Pragmatic Programmers, LLC.

Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein.

Our Pragmatic courses, workshops, and other products can help you and your team create better software and have more fun. For more information, as well as the latest Pragmatic titles, please visit us at https://pragprog.com.

For customer support, please contact support@pragprog.com.

For international rights, please contact rights@pragprog.com.

Copyright © 2016 The Pragmatic Programmers, LLC.

All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher.

Printed in the United States of America.

ISBN-13: 978-1-68050-123-0 Encoded using the finest acid-free high-entropy binary digits.

Book version: B1.0—March 2, 2016 Over the years that Core Data has been in production there have been a few complaints about the framework that struck home and were accurate. Easily the most well known complaint was regarding the ability to change a value in a large number of objects without requiring those objects to all be loaded into memory and then persisted back out to disk. The second largest, most well known complaint was regarding deleting a large number of objects. Again, the desire is to delete a large number of objects without having to load them into memory and then write back out to the persistent store again.

Both of these complaints only apply to the NSSQlite store. Since atomic stores such as the binary store require all of the data to be in memory, there is no issue with doing bulk changes or bulk deletes. But with the SQLite store, either of these changes can be incredibly CPU, disk and memory intensive.

With the introduction of iOS 8.0 and OS X Yosemite, the first complaint was addressed. With the introduction of iOS 9.0 and OS X El Capitan the second complaint was addressed.

Running with Scissors Both of these APIs work by making changes directly on disk. When we utilize either of these APIs, Core Data will construct the appropriate SQL calls and then pass them to SQLite. Nothing gets loaded into memory and therefore the API is executed very quickly. just slightly slower than SQLite itself.

If we can just make changes and/or deletes on disk and avoid having to load them all into memory, why don’t we just do that all of the time?

This API comes at a fairly signficiant cost. The changes that we make on disk are not passed to the NSManagedObjectContext instances in our application.

This means that we can very easily make a change to the data on disk and then our NSManagedObjectContext will try to make a different change and cause issues. When the first API was introduced they likened these APIs to running with scissors. You can do it, but there is greater risk.

First, data validation is performed in memory. When we make a change directly on disk we are by-passing the validation steps that Core Data normally performs. This means we can break a relationship and have dangling references, we can inject data that is not valid, etc. Worse, our application won’t notice the issue until it attempts to load the data later and then the user is left in a bad state.

Second, when the changes are made on disk the version number of the object is updated (as it should be). However, since nothing in memory knows of this

–  –  –

change the version number in memory won’t match. If Core Data were to attempt to do a save of an object in this state we will cause a merge conflict with a potentially negative outcome.

And of course there is the obvious issue. Our User Interface won’t know about the change and therefore the older data will still be displayed.

We can address these issues but that requires more code on our part. Lets start with looking at a bulk update.

Doing Bulk Updates Doing a bulk update is not a common event in most application lifecycles.

Selecting a large number of emails and marking them as read, or a large number of news items is a common example of doing a bulk update. While these situations do occur, they are unusual and should not be considered a core function of the application. Bulk updates are generally used to get us out of a coding or design “corner.” In our recipes application we are going to use the bulk update API to change the values of some of our recipes on the first launch after a migration. When we migrate the application to the fourth version we will add a boolean to indicate whether it is a favorite recipe or not and the default for that Recipe is NO. Once the migration is complete we then want to go through all of the recipes and change that default to YES for some of them.

To start with, we want to detect if this change has already been made or not.

There are several ways to accomplish this, and we have used other methods in the past. In this demonstration we are going to use the metadata that is contained with the persistent store to determine if the change has already been processed or not. This change to the initialization of our Core Data stack determines if we need to do any post migration processing or not.

Batch/PPRecipes/PPRDataController.m dispatch_queue_t queue = NULL;

queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(queue, ^{ NSFileManager *fileManager = [NSFileManager defaultManager];

NSURL *storeURL = nil;

storeURL = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

storeURL = [storeURL URLByAppendingPathComponent:@"PPRecipes.sqlite"];

NSError *error = nil;

NSPersistentStore *store = nil;

store = [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil

–  –  –

NSDictionary *metadata = [store metadata];

if (!metadata[FAVORITE_METADATA_KEY]) { [self bulkUpdateFavorites];

} Every persistent store contains metadata. The metadata resolves to a NSDictionary that we can query. We can also update this metadata as needed.

In this part of the code we are looking for a key named FAVORITE_METADATA_KEY.

If that key exists then we know that this particular bit of post processing has already been done. If the key is missing then we need to perform the task.


- (void)bulkUpdateFavorites { NSManagedObjectContext *moc = [self writerContext];

[moc performBlock:^{ NSBatchUpdateRequest *request = nil;

NSMutableDictionary *propertyChanges = nil;

NSPredicate *predicate = nil;

NSBatchUpdateResult *result = nil;

NSError *error = nil;

request = [[NSBatchUpdateRequest alloc] initWithEntityName:@"Recipe"];

NSDate *aMonthAgo = [self dateFrom1MonthAgo];

predicate = [NSPredicate predicateWithFormat:@"lastUsed = %@", aMonthAgo];

[request setPredicate:predicate];

propertyChanges = [NSMutableDictionary new];

propertyChanges[@"favorite"] = @(YES);

[request setPropertiesToUpdate:propertyChanges];

[request setResultType:NSUpdatedObjectIDsResultType];

result = [moc executeRequest:request error:&error];

if (!result) { ALog(@"Failed to execute batch update: %@\n%@", [error localizedDescription], [error userInfo]);

} //Notify the contexts of the changes [self mergeExternalChanges:[result result] ofType:NSUpdatedObjectsKey];

The -bulkUpdateFavorites method is where we are using the bulk update API. Once we are certain that we are executing on the proper queue for our main

–  –  –

NSManagedObjectContext we start off by creating a new NSBatchUpdateRequest. The NSBatchUpdateRequest is a subclass of NSPersistentStoreRequest, which is a class that was introduced in OS X 10.7 and iOS 5. A NSBatchUpdateRequest contains all of the properties that Core Data needs to execute our update directly on disk.

First, we initialize the request with the name of the entity we want to access.

We then pass it the predicate to filter the entities that are going to be updated.

In this example we are going to find all of the recipe entities that have been used in the last month and mark those as favorites. We construct a date object that represents one month ago and then pass that to the predicate and then pass the predicate into the NSBatchUpdateRequest.

In addition to the predicate, we also need to tell Core Data what properties need to be changed. We do this with a NSDictionary where the key is the property to change and the value is the new value to apply to the entity. As you can see, we do not have a lot of control over the changes here. There is no logic that we can apply. This is simple, brute-force, data changes at the database/persistent store level.

Once we pass the dictionary to the NSBatchUpdateRequest via the -propertiesToUpdate

we can define what kind of result we want back. We have three options:

• NSStatusOnlyResultType which won‘t return anything. If we are not going to do anything with the response there is no reason to ask for one.

• NSUpdatedObjectIDsResultType which will give us the NSManagedObjectIDs for each changed entity. If we are going to notify the application of the changes then we will want these to do the notification.

• NSUpdatedObjectsCountResultType which will give us a simple count of the number of entities altered.

In this example we are going to walk through updating the User Interface of the changes so we will ask for the NSManagedObjectID instances back.

Once we have the NSBatchUpdateRequest fully constructed we can then hand it off to any NSManagedObjectContext we want for processing. In this example I am using the writer context because it is closest to the NSPersistentStoreCoordinator.

But since this API does not notify the NSManagedObjectContext of the change, it really does not matter which context we use.

The call to -executeRequest: error: returns a simple id and it is up to us to know what the call is giving back to us. Since we set the -resultType to be NSUpdatedObjectIDsResultType we know that we are going to be getting an NSArray back.

If we get back a nil from this API call then we know that there was an error and we can respond to that error. As always in the code in this book, we are

–  –  –

going to treat the error as a fatal condition and crash. How to respond to those errors is a business decision determined by your application’s design and requirements.

Pages:   || 2 |

Similar works:

«ERZBISCHÖFLICHE URSULINENSCHULE HERSEL Gymnasium für Mädchen Rheinstraße 182, D-53332 Bornheim www.ursh.de / www.Ursulinenschule-Hersel.de Gy: Tel.: 02222-97710, Fax: 02222-9771150, E-mail: USH@Ursulinenschule-Hersel.de Erzbischöfliche Ursulinenschule Hersel, Rheinstr. 182, 53332 Bornheim Hersel, den 31. August 2015 Claudia Temming, StD‘ i. K. Internationale Austauschprogramme 2016 Englischsprachiges Ausland Liebe Eltern und Schülerinnen der Klassen 9, Wie Sie alle wissen, ist unsere...»

«Ed. '16 Die Editionsreihe der Berliner Festspiele erscheint bis zu sechsmal jährlich und präsentiert Originaltexte und Kunstpositionen. Bislang erschienen: Edition 1 Hanns Zischler, Großer Bahnhof (2012) Christiane Baumgartner, Nachtfahrt (2009) Edition 2 Mark Z. Danielewski, Only Revolutions Journals (2002 – 2004) Jorinde Voigt, Symphonic Area (2009) Edition 3 Marcel van Eeden, The Photographer (1945 – 1947), (2011 – 2012) Edition 4 Mark Greif, Thoreau Trailer Park (2012) Christian...»

«Die pilgernde Törin: Genesis, Revaluation, and Mirroring in Goethe's Wanderjahre Robin A. Clouser Goethe Yearbook, Volume 14, 2006, pp. 171-206 (Article) Published by North American Goethe Society DOI: 10.1353/gyr.2011.0443 For additional information about this article http://muse.jhu.edu/journals/gyr/summary/v014/14.clouser.html Access provided by PRESBYTERIAN UNIVERSITY OF EAST AFRICA (31 May 2013 13:40 GMT) ROBIN A. CLOUSER Die pilgernde TÃrin: Genesis, Revaluation, and Mirroring in...»

«Volume 5, Issue 5, May 2015 ISSN: 2277 128X International Journal of Advanced Research in Computer Science and Software Engineering Research Paper Available online at: www.ijarcsse.com A Survey on Data Mining Application & Tools V. S. Jagadheeswaran, 2V. N. Saranya Assistant Professor, Department of Information Technology, Dr N.G.P Arts and Science College, Coimbatore, India M.Phil Research scholar, Department of computer science, Dr N.G.P Arts and Science College, Coimbatore, India...»

«MANAGEMENT/ MISMANAGEMENT STYLES How to Identify a Style and What To Do About It by Ichak Kalderon Adizes, Ph.D. Director of Professional Services and CEO of The Adizes Institute Library of Congress Cataloging-in-Publication Data Adizes, Ichak. Management/Mismanagement Styles: how to identify a style and what to do about it © 2004 by Dr. Ichak Adizes. All rights reserved. No part of this book may be reproduced in any form, by any means (including electronic, photocopying, recording or...»

«Jahresschlussrede des Oberbürgermeisters am 18.12.2014 Sehr geehrte Damen und Herren, sehr geehrte Stadträtinnen und Stadträte, liebe Kolleginnen und Kollegen, liebe Mitbürgerinnen und Mitbürger, sehr geehrte Vertreter der Presse, das Jahr neigt sich dem Ende zu, Weihnachten und der Jahreswechsel stehen vor der Tür. Wir freuen uns auf Feiern im Familienund Freundeskreis, auf die geruhsame Zeit zwischen den Jahren. Dabei denken wir an ganz persönliche Erlebnisse und Vorhaben, aber auch an...»

«Lukas Adda Face to Face Handbuch Facebook-Marketing Auf einen Blick Auf einen Blick 1 Was bisher geschah. 2 Facebook-Marketing – User kennen und verstehen 3 Unternehmenskommunikation im radikalen Wandel 4 Welche Facebook-Präsenz zu Ihrer Unternehmung passt. 117 5 Ihre Ziele brauchen eine Strategie 6 Facebook-Integration und Umsetzung von Seiten 7 Laufende Betreuung von Facebook-Seiten 8 Auch für Facebook gilt: Mobil first! 9 Einsatz von Facebook Ads 10 Integration weiterer...»

«Discussion Paper Deutsche Bundesbank No 23/2015 Many a little makes a mickle: macro portfolio stress test for small and medium-sized German banks Ramona Busch Philipp Koziol Marc Mitrovic Discussion Papers represent the authors‘ personal opinions and do not necessarily reflect the views of the Deutsche Bundesbank or its staff. Editorial Board: Daniel Foos Thomas Kick Jochen Mankart Christoph Memmel Panagiota Tzamourani Deutsche Bundesbank, Wilhelm-Epstein-Straße 14, 60431 Frankfurt am Main,...»

«NICHOLAS SPARKS Wie ein Licht in der Nacht NICHOLAS SPARKS Wie ein Licht in der Nacht Roman Aus dem Amerikanischen von Adelheid Zöfel Die Originalausgabe erschien unter dem Titel Safe Haven bei Grand Central Publishing/Hachette Book Group USA, New York Verlagsgruppe Random House FSC-DEU-0100 Das für dieses Buch verwendete FSC ®-zertifizierte Papier Munken Premium Cream liefert Arctic Paper, Munkedals AB, Schweden. Copyright © 2010 by Nicholas Sparks Copyright © 2011 der deutschen Ausgabe...»

«    Terrence P McGarty CRISPRS AND CANCER White Paper No 111 April, 2014 We examine CRISPRs and Cas9 as a means to treat cancers on a genetic basis. This is a new and highly effective tool for genetic engineering and holds some promise for cancer therapy. Copyright 2014 Terrence P. McGarty, all rights reserved. DRAFT WHITE PAPER CRISPRS AND CANCER Notice  This document represents the personal opinion of the author and is not meant to be in any way ...»

<<  HOME   |    CONTACTS
2016 www.book.dislib.info - Free e-library - Books, dissertations, abstract

Materials of this site are available for review, all rights belong to their respective owners.
If you do not agree with the fact that your material is placed on this site, please, email us, we will within 1-2 business days delete him.