I'm coding for the iPhone and wondering if I need to include UIKit in every file that code or is there a better rule as to when to do so and when you don't have to?
Thanks!
UIKit is the iOS framework that implements the standard UI components for iOS applications. Building an app with UIKit is trivially easy. In all cases you'll use Xcode, Apple's IDE for developing for iOS and macOS. In Swift, you just put the statement import UIKit.
Navigate to the target and go to Build Phases and add UIKit to Link Binary With Libraries . From the Comments to this post: MonkeyBusiness: Sorry to waste your time. I had set the project up as MacOS rather than iOS.
UIKit is an "umbrella" framework, which imports a lot of other frameworks, including Foundation, so it really is imported. There's actually more to this than meets the eye. As it happens, Swift contains a re-implementation of the NSString APIs within the String class.
While the pch file is handy for pre-compiling headers for you, I really recommend that files import what they use. That makes it much easier to understand the dependencies, and much easier to reuse the code, including reuse across platforms (iPhone vs. Mac).
With that in mind, the answer is that you shouldn't import UIKit.h into every file. You should import it into every file that uses UIKit. That should be your View and Controller classes. Model classes should almost never use UIKit. They should generally import Foundation.h. Following this rule will make it easy to move your objects into other projects which may have different code in the .pch file, and easier to reuse your model classes on both iPhone and Mac.
I also typically do not recommend that you import UIKit.h or Foundation.h into subclasses of your own classes. I typically just import UIKit, AppKit or Foundation into the highest-level header file in my code. For example, if I have a UIView subclass called MYAbstractView that imports UIKit.h (to include the definition of UIView), and then add a MYConcreteView subclass, I would just import MYAbstractView.h.
Note that UIKit and AppKit both import Foundation already, so there's no reason ever to import both.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With