Eugene Gordin
Eugene Gordin

Reputation: 4107

Array of NSManagedObjects has null values in it after passing it to another method

In my app I'm using MagicalRecord for CoreData stack and I'm having a weird behavior of NSManagedObject. I have this method in my DB class that fetches all the entries of the Stuff entity from DB. I'm calling this method from another class, and inside of this getStuff method I'm getting correct values that getting print out in the log statement below.

-(NSArray*) getStuff
{
    NSManagedObjectContext * managedObjectContext = [NSManagedObjectContext MR_contextWithStoreCoordinator:self.psc];

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Stuff"];

    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"idNumber" ascending:YES];

    [request setSortDescriptors:[NSArray arrayWithObjects:sort, nil]];

    NSError *error = nil;
    NSArray *arr = [managedObjectContext executeFetchRequest:request error:&error];

    for (Stuff *stuff in arr) {
         NSLog(@"stuff fN: %@",stuff.idNumber);
    }

    if (arr)
       return arr;

    return [NSArray array];
}

However, the array that gets returned by this method to another class contains all these objects with null value in them.

// -- some othe class
// call DB to check if we have stuff there
NSArray* stuff = [database getStuff];

for (Stuff *stuff in stuff) {
         NSLog(@"stuff fN: %@",stuff.idNumber);
    }

Does anyone know why is this happening?! Any kind of help is highly appreciated!

Upvotes: 1

Views: 351

Answers (2)

Petro Korienev
Petro Korienev

Reputation: 4027

Assuming you setup your CoreData stack with MagicalRecord you can use [NSManagedObjectContext MR_contextForCurrentThread] instead of [NSManagedObjectContext MR_contextWithStoreCoordinator:self.psc]

Upvotes: 1

Martin R
Martin R

Reputation: 539685

Your getStuff method creates a new NSManagedObjectContext, which is (assuming that you compile with ARC) deallocated at the end of the method. Managed objects "live" in the context that they were created in. Accessing their properties after the context has been deallocated does not work.

Upvotes: 3

Related Questions