What can I do if two methods call each other and I don't want one of them to be publicly available in the header file?
I have two methods -a and -b. -a sometimes calls -b, and -b sometimes calls -a. Both methods are designed to be private and not called externally.
But I had to make one of them publicly available in the .h file, because otherwise the compiler would go crazy and throw a warning for one of them.
Is there any correct and effective solution for this problem?
a source to share
Traditionally, what you would do is define a category (something like @interface MyClass (MyClass_Private)
inside an implementation file that declares private methods). Apple recently introduced a feature called a class extension intended for this exact case. category specialization, but the class must implement methods when it was first defined. It looks like this:
@interface MyObject ()
- (void)setNumber:(NSNumber *)newNumber;
@end
a source to share
If you really want functions to be private, you need to declare them as static
. To eliminate a circular dependency, you must declare before another is defined. Here's a simple example:
static void b(); /* forward declaration */
static void a()
{
if (foo)
b(); /* forward-declared, so we're ok */
}
static void b()
{
if (bar)
a(); /* already defined, so we're ok */
}
This is all valid C, and so based on OP's comment, I assume it is indeed ObjC.
a source to share