[cfe-dev] Adding namespaces to Objective-C
Jens Ayton
mailing-lists.jens at ayton.se
Sat Nov 13 09:46:30 PST 2010
Ariel V Feinerman:
>
> Jens,
>
> do you mean?
>
> @interface MyClass : NSObject {
>
> }
> @namespace ns
> - method;
> @end
>
> @namespace my
> - method;
> @end
>
> // global
> @namespace
> - method;
> @end
Something along those lines, yes.
The methods could then be called as:
[foo ns method];
[foo my method];
[foo method];
If the last one wasn’t there, you could of course use an @using directive or similar to avoid the explicit namespace.
As for duck typing, which someone mentioned: the point is to partition selectors into non-overlapping sets. Calling [foo my method] could never resolve to a call to [foo method] any more than [foo my_method] would. The difference is that you can use @using to dispense with the explicit namespace. (Namespace resolution would be based on the static type of a variable, and not apply to id values.) On the other hand, if foo is, at runtime, of a different class with a “my method”, that would be called.
Selector expressions would always take an explicit namespace, as in @selector(my method). Ideally, there would be no mangling; SELs would simply contain/reference strings with a single space as a separator. (This also means sel_getName() wouldn’t need to do any processing.)
Preferably, the namespace identifier would be separated from the true name; the identifier needs only be unique at compile time, while the true name disambiguates at runtime.
@interface NSDictionary (JAUtilities)
@namespace se.jens.ayton.JAUtilities as jautil // Applies to end of @interface scope if not changed.
- (NSString *)stringForKey:(id)key;
@end
...
// These all call the same method.
NSDictionary *dict = whatever;
string = [dict jautil stringForKey:key];
@using jautil;
string2 = [dict stringForKey:key2];
string3 = [dict performSelector:@selector(jautil stringForKey:) object:key3];
string4 = [dict performSelector:NSSelectorFromString(@"se.jens.ayton.JAUtilities stringForKey:") object:key4];
NSDictionary *fake = [NSString string];
[fake jautil stringForKey:@"foo"];
// Runtime error: NSString does not respond to "se.jens.ayton.JAUtilities stringForKey:"
Incidentally, this was loosely inspired by ECMAScript 4th Edition, may it rest in peace and at length.
--
Jens Ayton
More information about the cfe-dev
mailing list