Question

I have a class called SLCollectionViewModel that, if initiated, will fetch the latest entry with Core Data. So far there is no problem with the initial view. The Collection View will display the visible entries correctly (and also shows them in log).

But the problem occurs when I try to scroll the view, or try to call [self.collectionView reloadData] explicitly. The error log is:

-[_PFArray retain]: message sent to deallocated instance 0x8de9ab0

I think my self.viewModel object is deallocated somewhere, but I can’t pinpoint what’s wrong with my approach. Here is my - (void)viewDidLoad method:

- (void)viewDidLoad
{
  [super viewDidLoad];

  self.viewModel = [SLCollectionViewModel new];

  [self.collectionView reloadData];

}

And here is my SLCollectionViewModel class:

- (instancetype) init {

  self = [super init];
  if(!self) return nil;

  _managedObjectContext = [[SLCoreDataStack defaultStack] managedObjectContext];

  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
  NSEntityDescription *entity = [NSEntityDescription
                                      entityForName:@"SLPost"
                                      inManagedObjectContext:_managedObjectContext];

  [fetchRequest setEntity:entity];
  // The _posts in an NSArray that saves all my NSManageObject
  // which will be used to populate the collection view.
  _posts = [_managedObjectContext executeFetchRequest:fetchRequest
                                                error:nil];

  return self;
}
Was it helpful?

Solution

I realize this is my own mistake for not creating the property properly. In my SLCollectionViewModel, the @property for NSArray *posts should use retain instead of assign.

Before: @property (nonatomic, assign) NSArray *posts;

After:

@property (nonatomic, retain) NSArray *posts;

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