Hi All,

I am trying to implement a singleton class which is a subclass of NSManagedObject, but it is not behaving as expected. The librarian singleton is supposed to keep a list of the data sources, which are added periodically. I'm trying to cache the Librarian as an instance variable of my App Controller so that I can access it easily. The app controller tries to create/retrieve the instance during its own init as follows:

<in AppController>
- (id)init
{
  if (self = [super init])
  {
    // a bunch of variables initialized here
    theLibrarian = [Librarian getLibrarianInstance];
  }
  return self;
}

What's totally weird is that my managed object context disappears midway through the following lines of code.

<in Librarian.m>
static Librarian *librarian = nil;
@implementation Librarian
@dynamic dataSources;
@dynamic numSources;

+ (Librarian *) getLibrarianInstance {
        NSError *error;
NSManagedObjectContext *moc = [[NSApp delegate] managedObjectContext]; // moc exists at this point
        if (librarian == nil) {
librarian = [NSEntityDescription insertNewObjectForEntityForName: @"Librarian"
                                    inManagedObjectContext: moc]; // moc 
becomes nil here !!!
          [moc insertObject: librarian];
          if (![moc save: &error]) {
                [[NSApplication sharedApplication] presentError:error];
          }
        }
        // [moc insertObject: librarian];
        return librarian;
}

I have two basic questions. Where is the best place to initialize a singleton for a Core Data application?

And secondly, what is the best way to access the managed object context. In my init, if I call

moc = [[NSApp delegate] managedObjectContext]; // value is nil
moc = [[[NSApplication sharedApplication] delegate] managedObjectContext]; // value is nil
coreDataDelegate = [[CoreDataLibrarian_AppDelegate alloc] init];
moc = [coreDataDelegate managedObjectContext]; // value exists

Surely you aren't supposed to alloc/init the AppDelegate class everywhere in your app just to get the context. What is the best way for accessing it throughout your code? (I notice most examples write // assume context exists.....)

Thanks in advance.

Daniel




_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [EMAIL PROTECTED]

Reply via email to