Question

I am trying to execute a fetch request to return a "workout" user object.

I will need this method in more than one controllers so I have moved it to it's own class. However when I move the following method from the controller to another class onSuccess or onFailure never executes - it just returns an empty array without any errors. I've tried putting managedObjectContext in as a parameter in case it was anything to do with that.

managedObjectContext is declared as:

 self.managedObjectContext = [[self.appDelegate coreDataStore] 
contextForCurrentThread];

The method in the class is declared as:

 -(NSArray*)getUserRecord:(NSManagedObjectContext *)managedObjectContext
{

NSFetchRequest *userFetch = [[NSFetchRequest alloc] initWithEntityName:@"User"];

[managedObjectContext executeFetchRequest:userFetch
                                     onSuccess:^(NSArray *results)
 {
     NSLog(@"Results %@", results);
     self.fetchedRecordsArray= [[NSMutableArray alloc] initWithArray:results];
     NSLog(@"Fetched Array %@", self.fetchedRecordsArray);
 }

                                     onFailure:^(NSError *error)
 {
     NSLog(@"DATABASE ERROR: %@", error);
     [[[UIAlertView alloc]initWithTitle:@"DATABASE ERROR" message:@"FATAL-unable to fetch workout object" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
 }];

return self.fetchedRecordsArray;

}

Why isn't onSuccess or onFailure being executed?

Was it helpful?

Solution

When your function returns your self.fetchedRecordsArray will always be nil because of blocks nature.

Try to do the following:

in .h file declare it like this:

- (void)getUserRecordWithContext:(NSManagedObjectContext *)managedObjectContext
             success:(void (^)(NSArray * users))success
             failure:(void (^)(NSError * error))failure;

And the implementation in .m file:

 - (void)getUserRecordWithContext:(NSManagedObjectContext *)managedObjectContext
             success:(void (^)(NSArray * users))success
             failure:(void (^)(NSError * error))failure; 
{

NSFetchRequest *userFetch = [[NSFetchRequest alloc] initWithEntityName:@"User"];

[managedObjectContext executeFetchRequest:userFetch
                                     onSuccess:^(NSArray *results)
 {
     NSLog(@"Results %@", results);
     self.fetchedRecordsArray= [[NSMutableArray alloc] initWithArray:results];
     NSLog(@"Fetched Array %@", self.fetchedRecordsArray);
     success(results);
 }

                                     onFailure:^(NSError *error)
 {
     NSLog(@"DATABASE ERROR: %@", error);
     failure(error);
 }];

}

Now when you call this function you can use your results in completion.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top