0

I have an app where I present VC1 to pick a game and VC2 to submit plays for the selected game. When a user segues back from VC2 to VC1 I want to retain the game data for the game they were playing. Since it's iOS 6.0, I am using UIManagedDocument to access Core Data for storing and retrieving the game data. And I am totally stumped by the problem I am facing and after spending countless hours, I am reaching out to the wise folks on this forum.

When I run the code below in the Simulator, everything works fine, the data gets stored and I am also able to retrieve it and show it if the user picks the same game as earlier on to play. Unfortunately on the device, I can see that the data gets stored on segue - I put a breakpoint and looked at the persistentStore using iExplorer - but as soon as I go back to VC2 selecting the stored game, the persistentStore seems to be overwritten or purged of all data. In the debugger I noticed that the _persistentStores NSArray property of the _persistentStoreCoordinator object for "UIManagedDocument" always shows 0 when retrieval is done on the device.

Any help is much appreciated!!!

- (void) addOrGetDataToGamesDatabase:(CNPUIManagedDocument *)document withFlag:(BOOL)getFlag {    
    if (getFlag) {
    NSLog(@"INSIDE addDataToGamesDatabase to get data");
    }
    else
    NSLog(@"INSIDE addDataToGamesDatabase to set data");

    dispatch_queue_t update = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0);
    dispatch_sync(update, ^{
    [document.managedObjectContext performBlockAndWait:^{
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Game"];
        request.predicate = [NSPredicate predicateWithFormat:@"game = %@", self.selectedGameID];
        NSError *error = nil;
        NSLog(@"Persistent Store Name = %@", [[document class] persistentStoreName]);
        NSArray *matches = [document.managedObjectContext executeFetchRequest:request error:&error];       
        NSLog(@"Fetch Error if any: %@ %@", error.debugDescription, [error userInfo]);


        if (!matches || matches.count >1) {
        NSLog(@"There is a problem with creating the game data");
        }

        //This is where it fails on the device as the match.count is always 0 as the fetch retrieves nothing
        else if ([matches count] == 0) {
        if (!getFlag) {
        // Code to initialize the game data in store
        }
        }
        else if ([matches count] == 1) {
        // Another fetch - nested
        if (!oTeammatches || [oTeammatches count] >1) {
            NSLog(@"There is a problem with creating the offense team data");
        }
        else if ([oTeammatches count] == 0) {
            if (!getFlag) {
              //Code to initialize the team data in store
           }
        }
        else if ([oTeammatches count] == 1) {
            OTeam *newOTeam = [oTeammatches lastObject];
            if (getFlag) {
                //Retrieves data
                //Shown by log lines beginning with "Getting"
            }
            else {
                //Sets/Saves data
                //Shown by log lines beginning with "Setting"
            }
         }

        }
    }];
    if (!getFlag) {
        [document updateChangeCount:UIDocumentChangeDone];
    }
    });
}

- (IBAction)pressBackButton:(UIButton *)sender {
    [self addOrGetDataToGamesDatabase:self.gamesDatabase withFlag:NO];
    if ((self.gamesDatabase.documentState & UIDocumentStateEditingDisabled) != UIDocumentStateEditingDisabled) {
    [self.gamesDatabase saveToURL:self.gamesDatabase.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:^(BOOL success) {
        if (success) {
           NSLog(@"DB save file path: %@", self.gamesDatabase.fileURL);
           NSLog(@"Saved!!!");
        }
        else
        NSLog(@"Unable to save");
    }];
    }
  [self performSegueWithIdentifier:@"BackToPickGame" sender:self];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
  //Some Initialization code

    if (!self.gamesDatabase) {
      NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
      url = [url URLByAppendingPathComponent:@"GameDB"];
      self.gamesDatabase = [[CNPUIManagedDocument alloc] initWithFileURL:url];
      NSLog(@"DB File URL generated: %@", url);
      NSLog(@"self.gameDatabase initialized");
    }

   [self addOrGetDataToGamesDatabase:self.gamesDatabase withFlag:YES];
   NSLog(@"Calling game with ID %@ , self.selectedGameID);
}

Some log info on the persistent store

DEVICE
First get on entering VC2
Printing description of document->_persistentStoreCoordinator: Printing description of document->_persistentStoreCoordinator->persistentStores: <_NSArrayM 0x1fd28ce0>(

)

First set in VC2 on exiting VC2
Printing description of document->_persistentStoreCoordinator: Printing description of document->_persistentStoreCoordinator->persistentStores: <_NSArrayM 0x1fd28ce0>( (URL: file://localhost/var/mobile/Applications/4DD2D219-5AC1-406F-8020-260B01E46E0C/Documents/GameDB/StoreContent/persistentStore) )

Second get on entering VC2
Printing description of document->_persistentStoreCoordinator: Printing description of document->_persistentStoreCoordinator->persistentStores: <_NSArrayM 0x211d4660>(

)

SIMULATOR
First get on entering VC2
Printing description of document->_persistentStoreCoordinator: Printing description of document->_persistentStoreCoordinator->persistentStores: <_NSArrayM 0x84e4b60>( (URL: file://localhost/Users/Rujul/Library/Application%20Support/iPhone%20Simulator/6.0/Applications/B187169B-8D32-4BB1-AB41-33DB76637D9C/Documents/GameDB/StoreContent/persistentStore) )

First set on exiting VC2
Printing description of document->_persistentStoreCoordinator: Printing description of document->_persistentStoreCoordinator->persistentStores: <_NSArrayM 0x84e4b60>( (URL: file://localhost/Users/Rujul/Library/Application%20Support/iPhone%20Simulator/6.0/Applications/B187169B-8D32-4BB1-AB41-33DB76637D9C/Documents/GameDB/StoreContent/persistentStore) )

Second get on entering VC2
Printing description of document->_persistentStoreCoordinator: Printing description of document->_persistentStoreCoordinator->persistentStores: <_NSArrayM 0xf777910>( (URL: file://localhost/Users/Rujul/Library/Application%20Support/iPhone%20Simulator/6.0/Applications/B187169B-8D32-4BB1-AB41-33DB76637D9C/Documents/GameDB/StoreContent/persistentStore) )

1 Answers1

0

Check all the overwrites in your code (like above in UIDocumentSaveForOverwriting). Log the exact values before and after. I am sure you are going to find the culprit in this way.

Also, check what you are doing in each prepareForSegue:.

BTW, I would recommend to perhaps refactor the confusing addOrGetDataToGamesDatabase business into two easily understood methods.

Mundi
  • 79,884
  • 17
  • 117
  • 140
  • Thx for your response. Not sure what values you want me to check after overwriting. I check the persistentStore on device when I set the values on exiting VC2 and I see that it gets populated. I have added some info on the state of the persistentStore. Would appreciate if you can look at it and comment. – user1989718 Jan 20 '13 at 21:42