我正在为 MKPolygon 类创建一个类别。您可以找到对此类的引用 here .我有两个要公开的公共(public)类方法和一些处理某些内部结构的“私有(private)”方法。我想要这样做的原因是因为,如您所见,可用于此类的方法是类方法,我想通过提供将返回的类方法(MKPolygon *)继续与此保持一致。此外,我将编写大量工作,不分解任务将违背良好的编码实践,当然也难以测试和阅读——这一点尤其重要,因为我将把它贡献给 github。
这是我在 XCode 中创建新类别时创建的头文件和实现文件。我现在打算使这些方法通用化以表达我的观点:
MKPolygon+MKPolygonStuff.h
#import <MapKit/MapKit.h>
@interface MKPolygon (MKPolygonStuff){
}
+(MKPolygon *)polygon:(MKPolygon *)poly1 doStuff:(MKPolygon *)poly2 onMap:(MKMapView *)map;
+(BOOL)polygon:(MKPolygon *)poly1 doesThisThing:(MKPolygon *)poly2;
@end
MKPolygon+MKPolygonStuff.m
@interface MKPolygon(){
}
+(void)calculateStuff;
@end
@implementation MKPolygon (MKPolygonStuff)
+(void)calculateStuff{
}
+(MKPolygon *)polygon:(MKPolygon *)poly1 doStuff:(MKPolygon *)poly2 onMap:(MKMapView *)map{
//do stuff and call other class methods to break up tasks
//[self calculateStuff];
}
+(BOOL)polygon:(MKPolygon *)poly1 doesThisThing:(MKPolygon *)poly2{
//returns boolean
//possibly call other class methods do some internals.
}
在我的实现文件中,我的界面有括号内的内容,但它给了我以下警告:
"Duplicate definition of category on interface..."
因此,在阅读了此处有关此问题的其他几个主题后,我决定将括号留空。这样做还可以让我拥有我绝对需要的实例变量,我不想将其“公开”。
现在我有一个警告位于 +(void)calculateStuff 旁边的实现部分下。
"Category is implementing a method which will also be implemented by its primary class".
我在网上搜索了这个警告,看看是什么导致了这个警告,如果编译器识别出你将覆盖类的一些内置功能,你似乎会收到这个警告。问题是,MKPolygon 类中没有 calculateStuff 方法,所以我不确定为什么会收到此警告。这里有什么地方我做错了吗?显然,我的私有(private)方法也必须是类方法,因为您不能从类方法调用实例方法。
如果有任何评论/建议/更正,我们将不胜感激。
最佳答案
如果calculateStuff
是私有(private)方法,只用在
MKPolygon (MKPolygonStuff)
类别,那么您根本不需要在接口(interface)中声明该方法。
只需从“MKPolygon+MKPolygonStuff.m”中删除@interface MKPolygon() ... @end
。
对于当前的 Xcode/clang 版本,您甚至不需要前向声明在实现 block 中定义和使用的方法。
关于iOS - 如何使用私有(private)方法创建类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16887244/