0

I need to access a NSManagedObject that gets set in another class, so I tried making a singleton that looks like this:

MyManager.h

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

@interface MyManager : NSObject {
    NSManagedObject *someProperty;
}

@property (nonatomic, retain) NSManagedObject *someProperty;

+ (id)sharedManager;

@end

MyManager.m

#import "MyManager.h"

@implementation MyManager

@synthesize someProperty;

#pragma mark Singleton Methods

+ (id)sharedManager {
    static MyManager *sharedMyManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedMyManager = [[self alloc] init];
    });
    return sharedMyManager;
}

- (id)init {
    if (self = [super init]) {
        someProperty = nil;
    }
    return self;
}

- (void)dealloc {
    // Should never be called, but just here for clarity really.
}

@end

I set in one class like this:

MyManager *sharedManager = [MyManager sharedManager];
sharedManager.someProperty = self.form;

but when I log it, it is null

NSLog(@"shared::%@", sharedManager.someProperty);

Im new to singletons so could use some advice.

BluGeni
  • 3,378
  • 8
  • 36
  • 64
  • Don't use them for things like this. Especially not with Core Data. Managed objects aren't thread safe. You can access the singleton anywhere so you're never guaranteed to be on the correct thread. Lots of reasons. Just don't do it. If you need to have a managed object in a couple of places then pass it around. – Fogmeister Nov 14 '13 at 14:42
  • @Fogmeister Hmm well it seemed I was directed to use a singleton in an earlier question I asked. Can you take a look and tell me what I should do? http://stackoverflow.com/questions/19964589/difficulty-accessing-property-on-another-class – BluGeni Nov 14 '13 at 14:45
  • My guess is self.form is already nil, the rest seems correct but if you put retain in your @property instead of strong it means you need to put dealloc and call super dealloc as you dont use arc. btw you should use arc! – Nicolas Manzini Nov 14 '13 at 15:20

2 Answers2

0

In core data, you cannot just set a property, you either insert a new object that particular entity or fetch it and used the fetched object to set property. I hope that when you are doing "set", you have created nsmanagedobject by insertion or fetch. If not, that might be the reason why it is null.

 NSManagedObject *someEntity = [NSEntityDescription insertNewObjectForEntityForName:@"someEntity" inManagedObjectContext:context];
 //after this
 someEntity.stringProperty = @"Blablabla";
Anand
  • 864
  • 10
  • 31
0

You should just fetch it again from the class U need it, but remember to save context before if U were changing it in that other class or thread...

AntonijoDev
  • 1,317
  • 14
  • 29