Monday, 26 August 2013

NSObject's category is available for every NSObject subclass even without any import of this category's .h file anywhere

NSObject's category is available for every NSObject subclass even without
any import of this category's .h file anywhere

Background.
Please consider the following steps:
1) In Xcode create a new "Single View Application".
2) Create a category NSObject+Extension.h and .m files:
// .h
@interface NSObject (Extension)
- (void)someMethod;
@end
// .m
@implementation NSObject (Extension)
- (void)someMethod {
NSLog(@"someMethod was called");
}
@end
3) Ensure that NSObject+Extension.m file is included into a main target.
4) Add the following line to AppDelegate:
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[NSString new] performSelector:@selector(someMethod)];
return YES;
}
5) Ensure that #import "NSObject+Extension.h line does not exists anywhere
in the app!
6) Run Application.
The output is
2013-08-27 04:12:53.642 Experimental[32263:c07] someMethod was called



Questions
I wonder if there is no any #import of this category anywhere in the app,
how is it even possible that NSString does still have NSObject+Extension
available? This behavior makes me feeling very bad about every Objective-C
category I declare because I want the categories I declare to be available
only in the scopes they are declared within. For example, I want NSObject
to be extended by Extension only in some class but not in the whole app
because its globalspace becomes "polluted" otherwise.
Is there a way to avoid this behavior? I do want my categories to work
only when I explicitly import them, not when I just have them linked to a
target I use to run.

No comments:

Post a Comment