Objective-C中的效用方法 [英] Utility methods in objective-c

查看:93
本文介绍了Objective-C中的效用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该在哪里将实用程序方法放置在Objective-c中?

Where should I place utility methods in objective-c?

例如由多个类调用的其他路径处理实用程序方法.

E.g. additional path handling utility methods which are called by multiple classes.

我看过一些示例,这些示例将它们放置在主appdelegate文件中,因此可供所有人使用.不过,这对我来说似乎有点怪异...

I have seen examples where they are placed in the main appdelegate file and are therefore available to all. This seems a bit weird to me though however...

推荐答案

您有一些选择:

  • 最简单的方法是为常见任务提供C函数集合(如果使用.m扩展名,则可以在C函数中使用Objective-C对象).例如,从您的代码中调用showAlertDialog().
  • 您可以拥有一个实用程序类",其中包含许多导入到每个文件的类方法.因此,例如,您可以调用+[MyUtilities showAlertDialog].在Java中,这与静态实用程序类最直接等效,但是在Objective-C中有点笨拙.
  • 正如保罗·林奇(Paul Lynch)所说,另一种选择是使用类别来扩展公共类.唯一的问题是它可能导致可维护性问题.它还仅在不需要访问ivars时才扩展现有的类.您可以为NSObject创建一个类别,该类别使您的所有对象都可以访问该方法,但是我强烈建议您这样做(这可能会导致严重的可维护性问题).
  • The simplest approach is to have a collection of C functions for common tasks (if you use a .m extension, you can use Objective-C objects within your C functions). From your code, for instance you would for instance call showAlertDialog().
  • You could have a "utility class" with a bunch of class methods that you import to every file. So for instance, you could call +[MyUtilities showAlertDialog]. This is the most direct equivalent to static utility classes in say Java, but it's a little clunky in Objective-C.
  • The other option, as Paul Lynch said, is to use categories to extend the common classes. The only problem with this is that it can lead to maintainability issues. It also only works to extend already-existing classes, and only when you don't need access to ivars. You could have a category for NSObject that would make the methods accessible from all your objects, but I would highly recommend against that (it could lead to severe maintainability headaches).

我个人使用选项1和3的组合.当我的功能与特定的现有类明确关联时,我将使用类别.否则,我将使用C函数.

Personally, I use a mix of options 1 and 3. When I have functionality that's clearly tied to a particular existing class, I use categories. Otherwise, I use C functions.

这篇关于Objective-C中的效用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆