Background
In Cocoa, Apple frequently makes use of the following paradigm:
[NSApplication sharedApplication]
[NSNotificationCenter defaultNotificationCenter]
[NSGraphicsContext currentContext]
[NSCalendar currentCalendar]
and so on.
They also will occasionally make use of a paradigm that I feel is far more legible when working with vast amounts of code.
NSApp //which maps to [NSApplication sharedApplication]
Goal
I'd love to be able to utilize this sort of global variable, both in my own classes, and in extensions to other classes.
MYClassInstance
NSDefaultNotificationCenter
NSCal /* or */ NSCurrentCalendar
and so on.
The "duh" Approach
#define
. Simply #define NSCal [NSCalendar currentCalendar]
, but as we all know by now, macros are evil (or so they say), and it just doesn't seem like the right Cocoa way to go about this.
Apple's Approach
The only source I could find regarding NSApp
was APPKIT_EXTERN id NSApp;
, which is not exactly reusable code. Unless I'm mistaken, all this code does is define NSApp
to be an id
the world around. Unfortunately unhelpful.
Close, but not Quite
In my searches, I've managed to find several leads regarding "global constants", however things like this:
extern NSString * const StringConstant;
are unfortunately limited to compile-time constants, and cannot map to the necessary class method.
Bottom Line
I'd love to be able to roll my own NSApp
-style global variables, which map to class methods like [NSNotificationCenter defaultNotificationCenter]
. Is this possible? If so, how should I go about it?
Further Attempts
I'm trying to implement specifically the framework singletons in the following way:
MySingletons.h
//...
extern id NSNotifCenter;
//...
MySingletons.m
//...
+(void)initialize
{
NSNotifCenter = [NSNotificationCenter defaultCenter];
}
//...
MyAppDelegate.m
//...
#import "MySingletons.h"
//...
//in applicationDidFinishLaunching:
[MySingletons initialize];
NSLog(@"%@", NSNotifCenter);
//...
However, this results in a compile-time error where the _NSNotifCenter symbol cannot be found.
Goal!
I'm currently working on an Objective-C class to encapsulate some of the framework singletons I've referred to in this question. I'll add the GitHub information here when I get it up.