I setup a few BLE connections in my view controller, SViewController, and I need to store the peripherals for use in other view controllers. I've tried creating an NSUserDefault object and storing the peripherals in there, but I got the error "Attempt to insert non-property value"
, and it never inserted. I then tried wrapping it up in an NSData object and storing it in NSUserDefaults, but got the error "-[CBConcretePeripheral encodeWithCoder:]: unrecognized selector sent"
and the app crashed. So that definitely did not work. I've also tried making the three CBPeripheral variables global, but I ran into a ton of issues with that. (I'm still very new to programming). I then looked into somehow caching them, but have read on here that it will not work and to not waste the time.
Does anyone know how to store a CBPeripheral object so that I can access it and initialize it in other view controllers?
Create a singleton that implements all of all your CBCentralManagerDelegate
methods. Then just create your own delegate methods for that singleton to message your viewControllers. That way you can easily use it in any class. As for storing the CBPeripherals, you can just place them inside of an NSMutableArray
contained inside of your singleton.
Check out this link on how to Create a Singleton Instance
(Oh and for where you say "Initialize it in other view controllers"..That should not ever be the case. But maybe you just mean to store the CFUUIDRef
? If you do that, you can just call retrievePeripherals:(NSArray*)
and get the peripheral object back wherever you want. If thats what you mean...)
来源:https://stackoverflow.com/questions/17455240/how-to-store-a-cbperipheral-for-use-in-other-views