0

In my UIViewController I call a method in another class which returns me a list of NSManagedObjects, which I instantiate in an array. Here is the code:

fileprivate var albumList = [Album]()

private func loadAlbums() {
    APIHandler().getUsersAlbums() {
        albums in
        self.albumList = albums
        self.collectionView?.reloadData()
    }
}

But this was causing my array to have nil properties once loadAlbums was finished and APIHandler's instance cleared. I solved this for now by having an instance of APIHandler on my UIViewController and calling the function from there, like this:

let api = SpotifyAPIHandler()
fileprivate var albumList = [Album]()

private func loadAlbums() {
    api.getUsersAlbums() {
        albums in
        self.albumList = albums
        self.collectionView?.reloadData()
    }
}

Still I am not happy with this. Why does this happen? How can I instantiate a completely new list?

  • 1
    NSManagedObjects is a class, not a pointer. Please rephrase your question. If you want to create a new managed object based on an existing object you should copy it. For details see: https://stackoverflow.com/questions/2730832/how-can-i-duplicate-or-copy-a-core-data-managed-object – ninjaproger Jul 06 '17 at 18:33
  • I don't see any blatant problems with your code. After your `loadAlbums()` is done, you should have all your album's saved. What do you mean your array has nil properties? Are you not seeing anything in your collectionView? Did you set your collectionView.dataSource and collecitonView.delegate? – cloudcal Jul 07 '17 at 00:46
  • My array has a valid NSManagedObject on each position, but if I try to get albumList[0].name, for instance, name will be nil – Guilherme Carvalho Jul 07 '17 at 09:06
  • Maybe is just because I have not much experience with NSManagedObjects but I was thinking if this is not because the NSManagedObjectContext resides in SpotifyAPIHandler? – Guilherme Carvalho Jul 07 '17 at 09:13

1 Answers1

0

I think what's happening is you're creating a new instance of APIHandler every time you're calling the loadAlbums() func instead what you can do is have a static refrence of ur APIHander in the APIHander class like so

class APIHander: NSObject {
    static let handler = APIHander()
}

Then you would call your API like this

private func loadAlbums() {
    APIHandler.handler.getUsersAlbums() {
        albums in
        self.albumList = albums
        self.collectionView?.reloadData()
    }
}
Harry Singh
  • 826
  • 5
  • 11
  • I don't think that's the issue as it's dealloc'd after `loadAlbum()` is finished - the data is saved every time so i think that's fine. – cloudcal Jul 07 '17 at 00:39