UIManagedDocument inserts objects into a background thread

This is my first stack overflow question, so please excuse me if I break any etiquette. I am also pretty new to creating Objective-C / app.

I am following the CS193P Stanford course, particularly CoreData lectures / demos. In Paul Hegarty’s Photomania app, he starts by presenting a table and populating the data in the background without interrupting the flow of the user interface. I am creating an application that lists enterprises in a local area (from an api that returns JSON data).

I created the categories according to the photo / photographer classes of Paul. Creating the classes themselves is not a problem where they are created.

A simplified data structure:
- Section
    - Sub-section
        - business
        - business
        - business
    - business
    - business
    - business

UIViewController , ( , , ). / URL- UIManagedDocument, . , , .

, Paul fetchFlickrDataIntoDocument:

-(void)refreshBusinessesInDocument:(UIManagedDocument *)document
{
dispatch_queue_t refreshBusinessQ = dispatch_queue_create("Refresh Business Listing", NULL);
dispatch_async(refreshBusinessQ, ^{
    // Get latest business listing
    myFunctions *myFunctions = [[myFunctions alloc] init];
    NSArray *businesses = [myFunctions arrayOfBusinesses];

    // Run IN document thread
    [document.managedObjectContext performBlock:^{

        // Loop through new businesses and insert
        for (NSDictionary *businessData in businesses) {
            [Business businessWithJSONInfo:businessData inManageObjectContext:document.managedObjectContext];
        }

        // Explicitly save the document.
        [document saveToURL:document.fileURL 
           forSaveOperation:UIDocumentSaveForOverwriting
          completionHandler:^(BOOL success){
              if (!success) {
                  NSLog(@"Document save failed");
              }
          }];
        NSLog(@"Inserted Businesses");
    }];
});
dispatch_release(refreshBusinessQ);
}

[myFunctions arrayOfBusinesses] JSON NSArray, -.

NSLog . , 0,006 , . 2 .

:

// The following typedef has been defined in the .h file
// typedef void (^completion_block_t)(UIManagedDocument *document);

@implementation ManagedDocumentHelper

+(void)openDocument:(NSString *)documentName UsingBlock:(completion_block_t)completionBlock
{
    // Get URL for document -> "<Documents directory>/<documentName>"
    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    url = [url URLByAppendingPathComponent:documentName];

    // Attempt retrieval of existing document
    UIManagedDocument *doc = [managedDocumentDictionary objectForKey:documentName];

    // If no UIManagedDocument, create
    if (!doc) 
    {
        // Create with document at URL
        doc = [[UIManagedDocument alloc] initWithFileURL:url];

        // Save in managedDocumentDictionary
        [managedDocumentDictionary setObject:doc forKey:documentName];
    }

    // If the document exists on disk
    if ([[NSFileManager defaultManager] fileExistsAtPath:[url path]]) 
    {
        [doc openWithCompletionHandler:^(BOOL success)
         {
             // Run completion block
             completionBlock(doc);
         } ];
    }
    else
    {
        // Save temporary document to documents directory
        [doc saveToURL:url 
      forSaveOperation:UIDocumentSaveForCreating 
     completionHandler:^(BOOL success)
         {
             // Run compeltion block
             completionBlock(doc);
         }];
    }
}

viewDidLoad:

if (!self.lgtbDatabase) {
    [ManagedDocumentHelper openDocument:@"DefaultLGTBDatabase" UsingBlock:^(UIManagedDocument *document){
        [self useDocument:document];
    }];
}

useDocument self.document .

, , , , , .

. , . - , , !

EDIT:

. , , - , , , ? , , , , , .

+5
2

.

UIManagedDocument, NSPrivateQueueConcurrencyType NSManagedObjectContext performBlock . :

// create a context with a private queue so access happens on a separate thread.
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
// insert this context into the current context hierarchy
context.parentContext = parentContext;
// execute the block on the queue of the context
context.performBlock:^{

      // do your stuff (e.g. a long import operation)

      // save the context here
      // with parent/child contexts saving a context push the changes out of the current context
      NSError* error = nil;
      [context save:&error];
 }];

. , ( UIDocument) ( does-a-core-data-parent-managedobjectcontext-need-to-share-a-concurrency-type-wi).

( ) - NSOperation -. , NSOperation :

//.h
@interface MyOperation : NSOperation

- (id)initWithDocument:(UIManagedDocument*)document;

@end

//.m
@interface MyOperation()

@property (nonatomic, weak) UIManagedDocument *document;

@end

- (id)initWithDocument:(UIManagedDocument*)doc;
{
  if (!(self = [super init])) return nil;

  [self setDocument:doc];

  return self;
}

- (void)main
{ 
  NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init];
  [moc setParentContext:[[self document] managedObjectContext]];

  // do the long stuff here...

  NSError *error = nil;
  [moc save:&error];

  NSManagedObjectContext *mainMOC = [[self document] managedObjectContext];
  [mainMOC performBlock:^{
    NSError *error = nil;
    [mainMOC save:&error];
  }];

  // maybe you want to notify the main thread you have finished to import data, if you post a notification remember to deal with it in the main thread...
}

, :

MyOperation *op = [[MyOperation alloc] initWithDocument:[self document]];
[[self someQueue] addOperation:op];

P.S. main NSOperation. main, , , . , , .

, .

+11

, , . UIDocument, count count - (void)autosaveWithCompletionHandler:(void (^)(BOOL success))completionHandler

, , " ".

0

All Articles