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 8482151
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T19:45:03+00:00 2026-06-10T19:45:03+00:00

I’ve just started playing with the iOS development and Core Data technology. What I

  • 0

I’ve just started playing with the iOS development and Core Data technology.

What I am trying to do is to insert object into the Core Data and then run fetch request within same context looking for the newly inserted object.

Here is the code I am using to insert the object:

+(Reward*) rewardForAction: (Actions) action
    inManagedObjectContext: (NSManagedObjectContext *) context {

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Reward"];
    NSPredicate *actionPredicate =
        [NSPredicate predicateWithFormat:@"action = %@",
         [NSString stringWithFormat:@"%i", action]];

    NSPredicate *todayPredicate =
        [NSPredicate predicateWithFormat:@"when > %@",
         [NSDate today]];

    NSLog(@"Today's midnight :%@", [NSDate today]);
    request.predicate =
        [NSCompoundPredicate andPredicateWithSubpredicates:
         [NSArray arrayWithObjects: actionPredicate, todayPredicate, nil]];

    NSError *error = nil;
    NSArray *matches = [context executeFetchRequest: request error: &error];

    Reward *reward = nil;
    if(!matches) {
        NSLog(@"ERROR: failed to retrieve rewards");
    } else if(matches.count > 0) {
        NSLog(@"WRONG: reward already exists");
    } else {
        reward = [NSEntityDescription insertNewObjectForEntityForName:@"Reward"
                                               inManagedObjectContext:context];
        reward.action = [NSNumber numberWithInt:action];
        reward.when = [NSDate date];
        reward.pointsEarned = [Reward getPointsForAction:action];
    }

    [Stats track: context];

    [context save:nil];

    return reward;
}

This code first checks if reward is already given today for some action and if not it gives a reward.

calling this method twice with same parameters, like this

[Reward rewardForAction:APPLICATION_LAUNCH
inManagedObjectContext: self.db.managedObjectContext];
[Reward rewardForAction:APPLICATION_LAUNCH
inManagedObjectContext: self.db.managedObjectContext];

expected to result in inserting only one object.

But, in fact it inserts two objects into the Core Data. In the debugger I see second fetch request returns no objects when one is already there.

Looks like NSFetchRequest does not see changes in the data store and operating will on old data. Am I missing something ?

EDIT:
I have also set up observer for the NSManagedObjectContextObjectsDidChangeNotification and when it gets called I am calculating sum of the points to reflect it on the UI. Unfortunately sum also does not contain points from the inserted object. Here is my code to calculate sum:

+(NSInteger) getPoints: (NSManagedObjectContext *) context {
    Stats * stats= [Stats get: context];

    NSArray *args = [NSArray arrayWithObject:
                     [NSExpression expressionForKeyPath:@"pointsEarned"]];
    NSExpression *ex = [NSExpression expressionForFunction:@"sum:"
                                                 arguments:args];

    NSExpressionDescription *ed = [[NSExpressionDescription alloc] init];
    [ed setName:@"result"];
    [ed setExpression:ex];
    [ed setExpressionResultType:NSInteger32AttributeType];

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setPropertiesToFetch:[NSArray arrayWithObject:ed]];
    [request setResultType:NSDictionaryResultType];

    /*if([stats intervalStartDate]) {
         NSPredicate *predicate =
            [NSPredicate predicateWithFormat:@"when >= %@", [stats intervalStartDate]];
             [request setPredicate:predicate];
    }*/    

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Reward"
                                              inManagedObjectContext:context];
    [request setEntity:entity];

    NSArray *results = [context executeFetchRequest:request error:nil];

    if(results && results.count > 0) {
        NSDictionary *resultsDictionary = [results objectAtIndex:0];
        NSNumber *resultValue = [resultsDictionary objectForKey:@"result"];
        return [resultValue intValue];
    } else {
        return 0;
    }    
}

Strangely enough when I stop the app on the simulator and run it again. I can see all points as I expect.

  • 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-10T19:45:04+00:00Added an answer on June 10, 2026 at 7:45 pm

    From

    reward.action = [NSNumber numberWithInt:action];
    

    I assume the “action” attribute is stored as NSNumber. You should use the same data type in the corresponding predicate:

    NSPredicate *actionPredicate = [NSPredicate predicateWithFormat:@"action = %@",
                                              [NSNumber numberWithInt:action]];
    

    ADDED: To your question about “NSManagedObjectContextDidSaveNotification” vs “NSManagedObjectContextObjectsDidChangeNotification”:

    A fetch request with NSDictionaryResultType only fetches the current state in the persistent store , and does not take into account any pending changes, insertions, or deletions in the context.

    You can find this information e.g. in the documentation of setIncludesPendingChanges:.

    This explains why your fetch request sees only changes that have been saved.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
this is what i have right now Drawing an RSS feed into the php,
I would like to run a str_replace or preg_replace which looks for certain words
I have a French site that I want to parse, but am running into
I am trying to render a haml file in a javascript response like so:
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this

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.