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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T03:08:04+00:00 2026-06-03T03:08:04+00:00

I am using the below code for a core data singleton. Below is my

  • 0

I am using the below code for a core data singleton. Below is my code. (based from NachoMan’s blog. However the code is from his gist.

// DataManager.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

extern NSString * const DataManagerDidSaveNotification;
extern NSString * const DataManagerDidSaveFailedNotification;

@interface DataManager : NSObject {
}

@property (nonatomic, readonly, retain) NSManagedObjectModel *objectModel;
@property (nonatomic, readonly, retain) NSManagedObjectContext *mainObjectContext;
@property (nonatomic, readonly, retain) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (nonatomic, readonly, retain) NSManagedObjectContext *managedObjectContext;

+ (DataManager*)sharedInstance;
- (BOOL)save;
- (BOOL)clearEntity:(NSString *)entityDescription;
- (NSManagedObjectContext*)managedObjectContext;

@end

// DataManager.m
#import "DataManager.h"

NSString * const DataManagerDidSaveNotification = @"DataManagerDidSaveNotification";
NSString * const DataManagerDidSaveFailedNotification = @"DataManagerDidSaveFailedNotification";

@interface DataManager ()

- (NSString*)sharedDocumentsPath;

@end

@implementation DataManager

@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
@synthesize mainObjectContext = _mainObjectContext;
@synthesize objectModel = _objectModel;
@synthesize managedObjectContext = _managedObjectContext;

NSString * const kDataManagerBundleName = nil;//@"AP";
NSString * const kDataManagerModelName = @"APData";
NSString * const kDataManagerSQLiteName = @"APData.sqlite";

+ (DataManager*)sharedInstance {
    static dispatch_once_t pred;
    static DataManager *sharedInstance = nil;

    dispatch_once(&pred, ^{ sharedInstance = [[self alloc] init]; });
    return sharedInstance;
}

- (void)dealloc {
    [self save];
}

- (NSManagedObjectModel*)objectModel {
    if (_objectModel)
        return _objectModel;

    NSBundle *bundle = [NSBundle mainBundle];
    if (kDataManagerBundleName) {
        NSString *bundlePath = [[NSBundle mainBundle] pathForResource:kDataManagerBundleName ofType:@"bundle"];
        bundle = [NSBundle bundleWithPath:bundlePath];
    }
    NSString *modelPath = [bundle pathForResource:kDataManagerModelName ofType:@"momd"];
    NSLog(@"Path: %@",modelPath);
    _objectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:[NSURL fileURLWithPath:modelPath]];

    return _objectModel;
}

- (NSPersistentStoreCoordinator*)persistentStoreCoordinator {
    if (_persistentStoreCoordinator) {
        NSLog(@"PersistentStore Exists %@",_persistentStoreCoordinator);
        return _persistentStoreCoordinator;
    }
    NSLog(@"Persistent Stored DOESN'T EXIST");

    // Get the paths to the SQLite file
    NSString *storePath = [[self sharedDocumentsPath] stringByAppendingPathComponent:kDataManagerSQLiteName];
    NSURL *storeURL = [NSURL fileURLWithPath:storePath];

    // Define the Core Data version migration options
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                 [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                 [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
                 nil];

    // Attempt to load the persistent store
    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.objectModel];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
                               configuration:nil
                                 URL:storeURL
                                 options:options
                                   error:&error]) {
        NSLog(@"Fatal error while creating persistent store: %@", error);
        abort();
    }
    NSLog(@"store: %@",_persistentStoreCoordinator);
    return _persistentStoreCoordinator;
}

- (NSManagedObjectContext*)mainObjectContext {
    if (_mainObjectContext)
        return _mainObjectContext;

    // Create the main context only on the main thread
    if (![NSThread isMainThread]) {
        [self performSelectorOnMainThread:@selector(mainObjectContext)
                       withObject:nil
                    waitUntilDone:YES];
        return _mainObjectContext;
    }

    _mainObjectContext = [[NSManagedObjectContext alloc] init];
    [_mainObjectContext setPersistentStoreCoordinator:self.persistentStoreCoordinator];

    return _mainObjectContext;
}

- (BOOL)save {
    if (![self.mainObjectContext hasChanges])
        return YES;

    NSError *error = nil;
    if (![self.mainObjectContext save:&error]) {
        NSLog(@"Error while saving: %@\n%@", [error localizedDescription], [error userInfo]);
        [[NSNotificationCenter defaultCenter] postNotificationName:DataManagerDidSaveFailedNotification
                                    object:error];
        return NO;
    }

    [[NSNotificationCenter defaultCenter] postNotificationName:DataManagerDidSaveNotification object:nil];
    return YES;
}

- (BOOL)clearEntity:(NSString *)entityDescription
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityDescription inManagedObjectContext:_managedObjectContext];
    [fetchRequest setEntity:entity];

    NSError *error;
    NSArray *items = [_managedObjectContext executeFetchRequest:fetchRequest error:&error]; 

    for (NSManagedObject *managedObject in items) {
        [_managedObjectContext deleteObject:managedObject];
        NSLog(@"%@ object deleted",entityDescription);
    }
    if (![_managedObjectContext save:&error]) {
        NSLog(@"Error deleting %@ - error:%@",entityDescription,error);

        return NO;
    }
    return YES;
}

- (NSString*)sharedDocumentsPath {
    static NSString *SharedDocumentsPath = nil;
    if (SharedDocumentsPath)
        return SharedDocumentsPath;

    // Compose a path to the <Library>/Database directory
    NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    SharedDocumentsPath = [libraryPath stringByAppendingPathComponent:@"Database"];

    // Ensure the database directory exists
    NSFileManager *manager = [NSFileManager defaultManager];
    BOOL isDirectory;
    if (![manager fileExistsAtPath:SharedDocumentsPath isDirectory:&isDirectory] || !isDirectory) {
        NSError *error = nil;
        NSDictionary *attr = [NSDictionary dictionaryWithObject:NSFileProtectionComplete
                                 forKey:NSFileProtectionKey];
        [manager createDirectoryAtPath:SharedDocumentsPath
           withIntermediateDirectories:YES
                    attributes:attr
                     error:&error];
        if (error)
            NSLog(@"Error creating directory path: %@", [error localizedDescription]);
    }

    return SharedDocumentsPath;
}

- (NSManagedObjectContext*)managedObjectContext {
    if (_managedObjectContext) {
        return _managedObjectContext;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    NSUndoManager *undoManager = [[NSUndoManager alloc] init];
    [_managedObjectContext setUndoManager:undoManager];
    [_managedObjectContext setPersistentStoreCoordinator:self.persistentStoreCoordinator];
    [_mainObjectContext setRetainsRegisteredObjects:YES];

    return _managedObjectContext;
}

@end

However, in the managedObjectContext if I add

NSUndoManager *undoManager = [[NSUndoManager alloc] init];
[_managedObjectContext setUndoManager:undoManager];

it will crash.

Crittercism logs show

SIGBUS
main (main.m:16)

0    CoreData 0x0033d940 -[NSManagedObject(_NSInternalMethods) _newSnapshotForUndo__] + 352
1    CoreData 0x00318fb1 -[NSManagedObjectContext(_NSInternalChangeProcessing) _registerUndoForOperation:withObjects:withExtraArguments:] + 193
2    CoreData 0x0031922f -[NSManagedObjectContext(_NSInternalChangeProcessing) _registerUndoForInsertedObjects:] + 63
3    CoreData 0x003148f8 -[NSManagedObjectContext(_NSInternalChangeProcessing) _processRecentChanges:] + 1384
4    CoreData 0x00314389 -[NSManagedObjectContext processPendingChanges] + 41
5    CoreData 0x002e8bd8 _performRunLoopAction + 216
6    CoreFoundation 0x0177d99e __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30
7    CoreFoundation 0x01714640 __CFRunLoopDoObservers + 384
8    CoreFoundation 0x016e04c6 __CFRunLoopRun + 1174
9    CoreFoundation 0x016dfd84 CFRunLoopRunSpecific + 212
10   CoreFoundation 0x016dfc9b CFRunLoopRunInMode + 123
11   GraphicsServices 0x023617d8 GSEventRunModal + 190
12   GraphicsServices 0x0236188a GSEventRun + 103
13   UIKit 0x007e2626 UIApplicationMain + 1163
14   My-App 0x284d main (main.m:16)
15   My-App 0x27b5 start + 53

Why is it crashing with these 2 lines when alot of SO posts say to use it? If I take these 2 lines out it won’t crash, I am just not able to use undo manager.

  • 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-03T03:08:04+00:00Added an answer on June 3, 2026 at 3:08 am

    I ended up clearing all cache and waiting a few days then trying again. It didn’t crash. It must have been something stuck in the cache.

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

Sidebar

Related Questions

I am using below code to send data to servlet HttpConnection c = (HttpConnection)Connector.open(http://localhost:8585/resposweb/resposweb?action=create_order;deviceside=true);
Hi I have created an array from core-data using: NSArray* invoiceItem =[fetchedResultsController fetchedObjects]; which
i am using below code to change the the font type of text view.
Currently i'm using below code which works well. $(#topperAtBaseLevel:visible, #lowerAtBaseLevel:visible, #midAtBaseLevel).hide(); any optimised code?
I am using below code to create a reminder in Google calendar (using Google
I am using below code for Embed MP3 Audio Files In Web Pages, <embed
I am trying to change desktop image using below code: NSError *anError = nil;
I wanted to generate a list view using below code. But after running this
As I created a Progress bar using below code in a on click method
In past, I am using Listview and using below code can show a particular

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.