How To Store a CBPeripheral For Use in Other Views

孤街浪徒 提交于 2019-12-05 20:28:28

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!