0
votes

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?

1

1 Answers

3
votes

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:

// =================================
// = Interface for hidden methods
// =================================
@interface SomeClass (hidden)

You should change it to:

// =================================
// = Interface for hidden methods
// =================================
@interface SomeClass ()

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:

@interface MyClass ()
-(void)bar;
@end

Then you can implement this function like normal