Reputation: 36003
I have a bunch of classes that are used by a lot of my projects. Some of these classes have to access some other special classes that I have created. Because I want to make the classes as much independent of others I do not want to have #import lines to cross import classes that do not belong together. I would like to access information on those classes without having to use #import lines.
Apple has some special stuff that can be accessed without importing anything. For example:
[[UIApplication sharedApplication] delegate]
or
[[UIScreen mainScreen] bounds]
how do I create classes like that. Classes that I can simply do a
[[MyClass sharedClass] property]
or
[[MyClass sharedClass] runThis]
and have access to it. Without having any #import line.
Attention because I am not talking about a regular singleton. A singleton you have to still import its file.
Is this possible?
Upvotes: 0
Views: 46
Reputation: 4561
You can do it....
Just make your imports in projectName-Prefix.pch
file
and use the content of imported file wherever you want.
You can find .pch
file in Resources folder.
Upvotes: 1
Reputation: 4805
The reason why you don't see an import for those classes is because you have the UIKit framework as a part of your project, which is effectively importing those classes' .h files into every class you create. It is possible to do what you are describing, however, in terms of separation, by taking advantage of dynamic dispatch and dynamic typing in objective-c, however you will lose compile-time error checking.
For example, I have a subclass of UIApplication delegate with an NSManagedInstance property by the name "managedObjectInstance. I do not import this subclass's .h file, but instead use the valueForKey: method like so:
[((NSObject*)[UIApplication sharedApplication].delegate) valueForKey: @"managedObjectContext"];
The NSObject cast is just because the delegate property of sharedApplication is an id, which means that it doesn't necessarily conform to KVO. To call a method that you know exists on a class without provoking a warning, you can use the performSelector: family of functions like so
[objectOfSomeClassWeDidntImport performSelector: @selector(amethodWeKnowExists)]
Upvotes: 2