Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7805641
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T02:17:15+00:00 2026-06-02T02:17:15+00:00

I have created few entities in context for saving it in db using AppCalendarEntity

  • 0

I have created few entities in context for saving it in db using

AppCalendarEntity *appCalendar = [AppCalendarEntity getInstanceWithManagedDocument:manageDocument];

After adding a few entities I execute flowing fetch request

 NSFetchRequest *requestToSeeIfCalendarWithIdExist = [NSFetchRequest fetchRequestWithEntityName:@"AppCalendarEntity"];
   NSArray *result = [managedDocument.managedObjectContext executeFetchRequest:requestToSeeIfCalendarWithIdExist error:&InternalError] ;

It returns me the result including only the entities I have added in context using first command and NOT the entries already saved in database. I have made sure that at this stage the document state is UIDocumentStateNormal.

When I add this line to already open document (UIDocumentStateNormal) it returns me the expected result, i.e. it fetch results from db as well as memory context which has not yet been saved to db.

[managedDocument openWithCompletionHandler:^(BOOL success) 
     {
       NSFetchRequest *requestToSeeIfCalendarWithIdExist = [NSFetchRequest fetchRequestWithEntityName:@"AppCalendarEntity"];
   NSArray *result = [managedDocument.managedObjectContext executeFetchRequest:requestToSeeIfCalendarWithIdExist error:&InternalError] ;
}

My question is
1- I expect that the result of query should be the same in both cases. Why it is not so in the above case.
2- To me if document state is UIDocumentStateNormal I should not be calling “openWithCompletionHandler” in context to open the document. In this particular scenario what difference it is making in NSFetchRequest which gives me the desired result after adding this.

Please let me know if I’m getting wrong

Here is the complete code

This is the complete code of the function

    + (void ) saveCalendarArrayInDbIfItAlreadyDoesNotExist : (NSArray*) appCalendarArray   managedDocument: (UIManagedDocument*) managedDocument completionBlock : ( void(^) (NSArray* ObjectSavedSuccesfully, NSError *InternalError)) handler
        {

        // i dont know why i have to do it :( if i dont add openWithCompletionHandler my query doesnt fetch result from db rather just do query in-memory context and not db
        [managedDocument openWithCompletionHandler:^(BOOL success) 
         {
            void (^completionHandler)(NSArray* , NSError* );
            completionHandler = [handler copy ];

            NSError *error = nil;
            NSMutableArray *array = [[NSMutableArray alloc] init];

            for (id appCalendar in appCalendarArray) {

                if([appCalendar isKindOfClass:[AppCalendarEntity class]])
                {
                    AppCalendarEntity *appCalendarEntity = (AppCalendarEntity*) appCalendar;
                    NSFetchRequest *requestToSeeIfCalendarWithIdExist = [NSFetchRequest fetchRequestWithEntityName:@"MyEntity"];
                    requestToSeeIfCalendarWithIdExist.predicate = [NSPredicate predicateWithFormat:@"identifier = %@", appCalendarEntity.identifier];
                    NSError *InternalError = nil; 
                   [requestToSeeIfCalendarWithIdExist setShouldRefreshRefetchedObjects:YES];
                    NSArray *result = [managedDocument.managedObjectContext executeFetchRequest:requestToSeeIfCalendarWithIdExist error:&InternalError] ;

                   // "result" is different when we encapsulate it in openWithCompletionHandler and when we don't…….MY PROBLEM

                   if(result == nil)
                    {

                         // return error
                    }

                    // 1 object always return that depict the in memory(context) object we created but not saved. I expect it should be zero because no object has yet been saved to database.. 
                    else if(result.count > 1)
                    {

                        [managedDocument.managedObjectContext deleteObject:appCalendar];
                    }
                    else
                    {
                        [array addObject:appCalendarEntity];
                    }
                }
                else
                {

                   // error handling
                }
            }

            if (error != nil)
            {
                 completionHandler (nil, error);
                 return;
            }

            // saving all the objects
             [ managedDocument updateChangeCount:UIDocumentChangeDone ];

    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T02:17:16+00:00Added an answer on June 2, 2026 at 2:17 am

    When using UIManagedDocument, you do not call save on the MOC because it implements auto-save. however, it needs to be told that an auto-save should take place at some point in the future.

    1. Get rid of that call to openWithCompletionHandler in that function (I know it was just there for purposes of debugging this problem).

    2. Replace

      [managedDocument.managedObjectContext save:&InternalError ]

    with

    [managedDocument updateChangeCount:UIDocumentChangeDone];
    

    This will notify the document that it can now be saved.

    EDIT

    First, I think you should get rid of the debugging hacks. You can add NSLog or NSAssert, but the rest of that stuff just makes it hard to tell why you want, and confuses the real issue.

    Second, what is your real goal here? I can see the name of the method, and I can see the code, but they do not match.

    There is so much “cruft” here, it is hard to understand your problem. I am going to repost your code, along with an edit to remove the “open” stuff, and annotate it with questions as code comments.

    Hopefully, this change will help you solve your problem.

    // First, the method name seems to indicate that some objects will be added
    // to the database.  however, the only database work in this method is removal.
    // I don't get it.
    + (void ) saveCalendarArrayInDbIfItAlreadyDoesNotExist : (NSArray*) appCalendarArray   managedDocument: (UIManagedDocument*) managedDocument
        {
            NSError *error = nil;
            NSMutableArray *array = [[NSMutableArray alloc] init];
    
            for (id appCalendar in appCalendarArray) {
                if([appCalendar isKindOfClass:[AppCalendarEntity class]]) {
                    // OK, we are filtering the array of objects.  We are only interested in
                    // objects of type AppCalendarEntity, and are going to use its identity
                    // property to look for objects of type MyEntity.
                    // What is the relationship between AppCalendarEntity and MyEntity?
                    AppCalendarEntity *appCalendarEntity = (AppCalendarEntity*) appCalendar;
                    NSFetchRequest *requestToSeeIfCalendarWithIdExist = [NSFetchRequest fetchRequestWithEntityName:@"MyEntity"];
                    requestToSeeIfCalendarWithIdExist.predicate = [NSPredicate predicateWithFormat:@"identifier = %@", appCalendarEntity.identifier];
                    NSError *InternalError = nil; 
                   [requestToSeeIfCalendarWithIdExist setShouldRefreshRefetchedObjects:YES];
                    NSArray *result = [managedDocument.managedObjectContext executeFetchRequest:requestToSeeIfCalendarWithIdExist error:&InternalError];
    
                   // OK, now we just got a result from searching for a MyEntity, where
                   // its identifier is the same as the appCalendarEntity.
                   if(result == nil)
                   {
                       // return error
                   }
                    // 1 object always return that depict the in memory(context) object we created but not saved. I expect it should be zero because no object has yet been saved to database.. 
                    else if(result.count > 1)
                    {
                        // I am extremely confused by this code.  First, why are you
                        // checking for more than 1 object?  The method name indicates
                        // you are going to insert something.  Furthermore, you are only
                        // deleting one object.  How many do you expect?  Also, why are
                        // you deleting an appCalendar?  You were searching for a MyEntity.
                        // If an appCalendar is a MyEntity, then that's terrible naming.
                        // Furthermore, it would explain why you are finding it...
                        // because you create entities by inserting them in a MOC to
                        // begin with!
                        [managedDocument.managedObjectContext deleteObject:appCalendar];
                    }
                    else
                    {
                        // Even more confusion.  You are adding this object to an internal
                        // array, not the database.  Furthermore, you are doing it if there
                        // are either 0 or 1 MyEntity objects in the database with matching
                        // identifier.
                        [array addObject:appCalendarEntity];
                    }
                }
            }
    
            // saving all the objects
            // OK - but the only thing being saved are the ones you deleted...
            [ managedDocument updateChangeCount:UIDocumentChangeDone ];
    }
    

    Finally, if my hunch is correct, and the calendar objects are actually MyEntity objects, they are already in the MOC – because that’s how they get created. When you do a fetch, you can force the search to ignore pending changes (as noted in one of my previous comments) and only accept saved changes.

    If you want to ignore pending changes,

    fetchRequest.includesPendingChanges = NO;
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am following the tutorial on sharparchitecture.net. I have created a few entities using
I'm using the python api and have created a few orphaned blobs during testing.
I have created a few small flash widgets that stream .mp3 audio from an
I have setup BPS and have created a few BPEL processes which i can
I have created a tab control and few forms. Each form opens in a
I have created a small flash CS4 project that has a few custom components
I have a few divs created dynamically in Javascript.I was wondering if it is
We have few components like libraries dlls When initially created I ran the following
I created an Android project a few months ago and now have to automate
I have some entities created with LINQ-to-SQL. Six of these entities (representing values primarily

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.