ecotax
ecotax

Reputation: 1953

Can I declare a non-public method in an Objective C Category, and if so, how?

To work with JSON data I receive from the AFNetworking library in my app, I'm defining a category on NSDictionary in a file NSDictionary+JSON.h:

@interface NSDictionary (JSON)
- (NSString *) name;
- (NSString *) extension;
...
@end

In my implementation of these methods, I want to declare and use a helper method that I don't want to put in the header file, because it's an implementation detail only:

- (NSString *) valueForKeyFromDictionaryOrIndexes:(NSString *)key;

My implementation file NSDictionary+JSON.m looks like this:

#import "NSDictionary+JSON.h"

@interface NSDictionary()
// Putting my method declaration here produces a warning.
...
@end


@implementation NSDictionary (JSON)

- (NSString *) valueForKeyFromDictionaryOrIndexes:(NSString *)key {

    NSString * value = [self valueForKey:key];

    // implementation details omitted

    return value;
}

- (NSString *) name {

    return [self valueForKeyFromDictionaryOrIndexes:@"Name"];
}

- (NSString *) extension {

    return [self valueForKeyFromDictionaryOrIndexes:@"Extension"];
}

...

@end

This works fine, so in that sense there is no real problem. But: my helper method has never been declared before being defined. I feel a bit uncomfortable about that. If I put the declaration within the @interface ... @end part in the implementation file, at the comment position (which I assumed would be the correct place to declare a non-public method), I receive a warning:

category is implementing a method which will also be implemented by its primary class

I tried fixing that by replacing @interface NSDictionary() with @interface NSDictionary(JSON) but that, of course, gives me a different warning:

duplicate definition of category 'JSON' on interface 'NSDictionary'

Fair enough, that's indeed the same as the one in my header file, so that's not a proper solution. Which leaves me wondering: what's the proper way/place to declare a non-public method in a category implementation?

Upvotes: 1

Views: 100

Answers (1)

NRitH
NRitH

Reputation: 13903

There's no need at all to declare a "private" Obj-C method inside your @interface.

Upvotes: 1

Related Questions