如何实现“私有” Objective-C 中的 Singleton 类中的方法
我在 Objective-C 中有一个单例 MyClass。在单例中,假设我有一个方法 -(void)foo
,其他类使用 [[MyClass sharedManager] foo]
发送消息。
在 foo 中,我调用了在 MyClass 中实现的“私有”方法 -(void)bar
。所以像这样:
-(void)foo {
[self bar];
}
因为我希望 bar 是私有的(在 Objective-C 中尽可能私有),所以我的 MyClass.h 文件中没有 bar 的定义。这会在 XCode 中导致警告:
找不到方法“-bar”(返回类型默认为“id”)
如何在单例类中拥有私有方法?
I have a singleton MyClass in Objective-C. In the singleton, let's say I have a method -(void)foo
that other classes message using [[MyClass sharedManager] foo]
.
In foo, I call a "private" method -(void)bar
implemented in MyClass. So something like this:
-(void)foo {
[self bar];
}
Since I want bar to be private (as private as possible in Objective-C), I don't have the definition of bar in my MyClass.h file. This causes a warning in XCode:
Method '-bar' not found (return type defaults to 'id')
How do I have private methods in my singleton class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用“类别”。这里描述的是:
http://macdevelopertips.com/objective-c/private-methods.html
基本上,您只需在实现文件中声明方法即可。类别还可用于其他用途,但这是一种非常简单的使用方式。
我对该网站上的示例代码唯一要更改的是,他们在实现文件的顶部有这样的内容:
您应该将其更改为:
这使其成为“匿名类别”。您不需要命名它,因为您正在同一文件中实现这些函数。
因此,如果你想在你的类中声明一个私有方法 -(void)bar 你会这样做:
然后你可以像平常一样实现这个函数
You should use a "category". It is described here:
http://macdevelopertips.com/objective-c/private-methods.html
Basically you just declare the methods within the implementation file. Categories can be used for other things but this is a pretty simple way to use them.
The only thing I would change from the example code on that site, is that they have this at the top of the implementation file:
You should change it to:
This makes it an "Anonymous Category". You don't need to name it because you are implementing the functions right here in the same file.
So if you want to declare a private method -(void)bar in your class you would do:
Then you can implement this function like normal