3

I'm using PINCache (https://github.com/pinterest/PINCache) to cache some objects into my app. So, using objC it is perfect, but when I wanna cast with swift I had EXC_BAD_ACCESS

When I call objectForKey

- (id <NSCoding>)objectForKey:(NSString *)key;

And I have nothing cached for that key, but Swift understand that the object is an NSConding. So, if I have values into a key, I have no problems.

So, how can I cast this NSCoding result and compare with nil value. I only need to know if the object return from PINCache is nil (never cached).

I've already tried:

private func setupTrucks() {
    let trucksCached: AnyObject? = PINDiskCache.sharedCache().objectForKey(TruckCache.key)
    if let _truck = trucksCached as? [Truck] { //EXC_BAD_ACCESS here
        print(_truck)
    }
}

private func setupTrucks() {
    let trucksCached = PINDiskCache.sharedCache().objectForKey(TruckCache.key) as [Truck] //EXC_BAD_ACCESS here
    if trucksCached.count > 0 {
        print(_truck)
    }
}
Klevison
  • 3,342
  • 2
  • 19
  • 32

1 Answers1

2

It looks like PINCache is not defining the return types of the synchronous objectForKey: methods as __nullable. Without that Swift doesn't know that the return type is optional.

I submitted a PR, which has already been accepted, that should fix the problem. You should now be able to do something like:

let trucksCached: AnyObject? = PINDiskCache.sharedCache().objectForKey("truck_key")
if let _truck = trucksCached as? Truck {
    print(_truck)
}
rcancro
  • 61
  • 2
  • Thanks for the PR :) Now I can do: `let truckCached = PINDiskCache.sharedCache().objectForKey(TruckCache.key) as? [Truck] ?? [Truck]()` – Klevison Jul 22 '15 at 02:55