类别中的私有方法,使用匿名类别

| 我正在NSDate上创建一个类别。它具有一些实用程序方法,这些方法不应成为公共接口的一部分。 如何将它们设为私有? 在类中创建私有方法时,我倾向于使用“匿名类别”技巧:
@interface Foo()
@property(readwrite, copy) NSString *bar;
- (void) superSecretInternalSaucing;
@end

@implementation Foo
@synthesize bar;
.... must implement the two methods or compiler will warn ....
@end
但它似乎无法在另一个类别中使用:
@interface NSDate_Comparing() // This won\'t work at all
@end

@implementation NSDate (NSDate_Comparing)

@end
在类别中拥有私有方法的最佳方法是什么?     
已邀请:
        应该是这样的:
@interface NSDate ()

@end

@implementation NSDate (NSDate_Comparing)

@end
    
        它应该是
@interface NSDate (NSDate_Comparing)
就像
@implementation
是否将@interface放在其自己的.h文件中,取决于您自己,但是大多数时候,您都想这样做-因为您想在其他几个类/文件中重用该类别。 确保为自己的方法加上前缀,以免干扰现有方法。或将来可能的增强。     
        我认为最好的方法是在.m文件中创建另一个类别。下面的例子: APIClient + SignupInit.h
@interface APIClient (SignupInit)

- (void)methodIAddedAsACategory;
@end
然后在APIClient + SignupInit.m中
@interface APIClient (SignupInit_Internal)
- (NSMutableURLRequest*)createRequestForMyMethod;
@end

@implementation APIClient (SignupInit)

- (void)methodIAddedAsACategory
{
    //category method impl goes here
}
@end

@implementation APIClient (SignupInit_Internal)
- (NSMutableURLRequest*)createRequestForMyMethod
{
    //private/helper method impl goes here
}

@end
    
        为了避免其他提议的解决方案具有警告,您可以只定义函数而不声明它:
@interface NSSomeClass (someCategory) 
- (someType)someFunction;
@end

@implementation NSSomeClass (someCategory)

- (someType)someFunction
{
    return something + [self privateFunction];
}

#pragma mark Private

- (someType)privateFunction
{
    return someValue;
}

@end
    

要回复问题请先登录注册