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

  • Home
  • SEARCH
  • 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 8304301
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T17:48:18+00:00 2026-06-08T17:48:18+00:00

I’m developing an iOS app using Core Data. And I have a Log entity

  • 0

I’m developing an iOS app using Core Data. And I have a Log entity with one-to-many relationships with Audio, Photo entities, and one-to-one relationship with Status entity. The log also has text, longitude, latitude properties. I can create the log, change its properties, add status entity, these changes would display right, until I quit the App. All the changes would disappear, and I was looking at the sqlite database, all these changes were never persisted in the database. In the database, the status object will just be created, but not linked to the log object.

But if I add an audio or photo object into the log.audioSet or log.photoSet, the changes I made to log, including the changes to text or status, will suddenly be saved into the database.

So it seems the changes are only maintained in the NSManagedObjectContext, until a related one_to_many entity is added and the [[LTLogStore sharedStore] saveChanges] will suddenly start to work.

I am using a singleton to manage the NSManagedObjectContext. Any ideas?

I would post some code if it’s relevant. Thanks.

UPDATE: I’m not sure these code is enough. But basically everything works, and displays, it just doesn’t save to the database. I’m using the mogenerator to set the text and latitude, but since everything is in the context. I am not sure this is the code you might need.

CODE:

@interface LTLogStore : NSObject{
}

+ (LTLogStore *)sharedStore;

- (void)removeItem:(Log *)p;

- (Log *)createItem;

- (BOOL)saveChanges;

@property(nonatomic, strong) NSFetchedResultsController *resultsController;
@property(nonatomic, strong) NSManagedObjectModel *model;
@property(nonatomic, strong) NSManagedObjectContext *context;

@end


@implementation LTLogStore
@synthesize resultsController;
@synthesize context, model;

+ (LTLogStore *)sharedStore
{
    static LTLogStore *sharedStore = nil;
    if(!sharedStore){
        sharedStore = [[super allocWithZone:nil] init];
    }

    return sharedStore;
}

+ (id)allocWithZone:(NSZone *)zone
{
    return [self sharedStore];
}

- (id)init 
{
    self = [super init];
    if(self) {                
        model = [NSManagedObjectModel mergedModelFromBundles:nil];

        NSPersistentStoreCoordinator *psc = 
        [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];

        // Where does the SQLite file go?    
        NSString *path = [self itemArchivePath];
        NSURL *storeURL = [NSURL fileURLWithPath:path]; 

        NSError *error = nil;

        if (![psc addPersistentStoreWithType:NSSQLiteStoreType 
                               configuration:nil
                                         URL:storeURL
                                     options:nil
                                       error:&error]) {
            [NSException raise:@"Open failed"
                        format:@"Reason: %@", [error localizedDescription]];
        }

        // Create the managed object context
        context = [[NSManagedObjectContext alloc] init];
        [context setPersistentStoreCoordinator:psc];

        // The managed object context can manage undo, but we don't need it
        [context setUndoManager:nil];

    }
    return self;
}



- (NSFetchedResultsController *)resultsController {
    if (resultsController !=nil) {
        return resultsController;
    }

    NSFetchRequest *request = [[NSFetchRequest alloc] init];

    NSEntityDescription *e = [[model entitiesByName] objectForKey:@"Log"];
    [request setEntity:e];

    NSSortDescriptor *sd = [NSSortDescriptor 
                            sortDescriptorWithKey:@"created_at"
                            ascending:NO];
    [request setSortDescriptors:[NSArray arrayWithObject:sd]];
    [request setReturnsObjectsAsFaults:NO];


    NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc]
                                                            initWithFetchRequest:request 
                                                            managedObjectContext:context
                                                            sectionNameKeyPath:nil cacheName:@"Root"];

    NSError *error;
    BOOL success = [fetchedResultsController performFetch:&error];
    if (!success) {
        //handle the error
    }

    return fetchedResultsController;
} 



- (NSString *)itemArchivePath
{
    NSArray *documentDirectories =
    NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                        NSUserDomainMask, YES);

    // Get one and only document directory from that list
    NSString *documentDirectory = [documentDirectories objectAtIndex:0];

    NSString *storePath = [documentDirectory stringByAppendingPathComponent:@"store.data"];
    return storePath;
}


- (BOOL)saveChanges
{
    NSError *err = nil;
    BOOL successful = [context save:&err];
    NSLog(@"Saving changes to the database");
    if (!successful) {
        NSLog(@"Error saving: %@", [err localizedDescription]);
    }
    return successful;
}

- (void)removeItem:(Log *)l
{
    [context deleteObject:l];
    [self saveChanges];
}



- (Log *)createItem
{    
    Log *p = [NSEntityDescription insertNewObjectForEntityForName:@"Log"
                                            inManagedObjectContext:context];
    [self saveChanges];
    return p;
}

@end



@interface Log : _Log {
}

//these two are some custom convenience methods for location attributes, but it does the work of setting the longitude and latitude value in the log object, but calling the [[LTLogStore sharedStore] saveChanges] still won't save it into the database.
-(CLLocation*)location;
-(void)setLocation:(CLLocation*)location;

//this all works 
-(Audio*)newAudio;
-(Audio*)newAudioWithPath:(NSString*)audioPath;
//after calling this method, even the log.text changes will be saved to the database.
-(void)addAudioWithPath:(NSString*)audioPath;    
-(void)removeAudio:(Audio*)audio;

@end



#import "Log.h"
#import "Audio.h"
#import "LTLogStore.h"

@implementation Log

-(CLLocation*)location{
    if (!self.longitude || !self.latitude) {
        return nil;
    }
    CLLocation *l = [[CLLocation alloc] initWithLatitude:[self.latitude doubleValue] longitude:[self.longitude doubleValue]];
    return l;
}

-(void)setLocation:(CLLocation*)location{
    if (location==nil) {
        self.latitude = nil;
        self.longitude = nil;
    }
    self.latitude = [NSNumber numberWithDouble: location.coordinate.latitude];
    self.longitude = [NSNumber numberWithDouble:location.coordinate.longitude];
    [[LTLogStore sharedStore] saveChanges];
}


-(Audio*)newAudio{
    Audio *a = [Audio new];
    a.log = self;
    return a;
}

-(Audio*)newAudioWithPath:(NSString*)audioPath{
    Audio *new = [self newAudio];
    [new setKey:audioPath];
    return new;
}

-(void)addAudioWithPath:(NSString*)audioPath{
    Audio *new = [self newAudio];
    [new setKey:audioPath];
    [[LTLogStore sharedStore] saveChanges];
}

-(void)removeAudio:(Audio*)audio{
    [self.audiosSet removeObject:audio];
    [[[LTLogStore sharedStore] context] deleteObject:audio];
    [[LTLogStore sharedStore] saveChanges];
}

@end

UPDATE:

Problem solved, see answer.

UPDATE QUESTION: Why is my overriding causing the problem? Can someone explain the cause behind the magic of Core Data or maybe KVO behind scene?

  • 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-08T17:48:20+00:00Added an answer on June 8, 2026 at 5:48 pm

    Problem solved, I overrode the willChangeValueForKey method in the Log class, which caused the problem, I thought the code is irrelevant. But it IS:

    - (void)willChangeValueForKey:(NSString *)key{
        //I added the following line to fix my problem
        [super willChangeValueForKey:key];
    
        //this is the original line, I want to have this 
        //because I want to have a isBlank property 
        //so I can see if the user modified the log
        _isBlank = false;
    
        //I tried to also add the following line to be safe.
        //turns out this line is not needed, and it will make the problem occur again
        //[super didChangeValueForKey:key];
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using Paperclip to handle profile photo uploads in my app. They upload
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
We're building an app, our first using Rails 3, and we're having to build
I have thousands of HTML files to process using Groovy/Java and I need to
I'm making a simple page using Google Maps API 3. My first. One marker
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and

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.