关于 Cocoa Touch 中单例的问题
我对 OOP 和设计模式很陌生,但我之前已经实现过一次 Singleton 模式,以便在不同的 ViewController 之间传递静态数组和字符串对象。
我想知道是否有一种简单的方法可以让我的所有 ViewController 监听手势或事件,然后在发生所述手势/事件后执行一些代码。我正在考虑使用 UIGestureRecognizer
对象或 UIResponder
类的 motionBegan
方法。
我已经通过创建一个新的 UIWindow 类、在其中放置代码并将 MainWindow.xib 的类更改为我的自定义类来完成此工作。这可行,并且是一个很好的解决方案,但我仍然想知道是否有非 IB 方式来实现该解决方案(例如,单例)
提前感谢您的指导。
示例代码非常感谢!
I'm quite new to OOP and design patterns, but I've implemented the Singleton pattern once before to pass static arrays and string objects between different ViewControllers.
I was wondering if there was an easy way to have all my ViewControllers listen for a gesture or event, and then execute some code once said gesture/event occurs. I was thinking of either using the UIGestureRecognizer
object or motionBegan
method of the UIResponder
class.
I've already gotten this working by making a new UIWindow
class, lodging the code in there, and changing the class of MainWindow.xib
to my custom class. This works, and is a nice solution, but I'm still wondering if there's a non-IB way of implementing this solution (e.g., singletons)
Thanks ahead of time for your guidance.
Sample code is greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你继承了 UIWindow 吗?这是非常不常见的。了解 UIApplication 委托对象和一般委托模式。它基本上是您应用程序在 Cocoa 中的主要单例。
如果您不想传递它,您可以随时通过调用来检索应用程序的委托
You subclassed UIWindow? That's very uncommon. Read about the UIApplication delegate object, and the delegate pattern in general. It's basically your app's main singleton in Cocoa.
If you don't want to pass it around, you can always retrieve the app's delegate by calling
如果您希望向多个未连接的对象/控制器通知单个事件,您可以按照您喜欢的方式触发它(来自控件或手势识别器的目标/操作)。
您可能需要查看
NSNotificationCenter
和NSNotification
,您可能会列出多个对象以用于事件/更改的通知。If you want lots of unconnected objects/controllers to be notified of a single event, you can trigger it however you like (target/action from a control(s) or gesture recognizer(s)).
You might want to look into
NSNotificationCenter
andNSNotification
, you could have multiple objects listing for the notification of the event/change.