mangerlahn
mangerlahn

Reputation: 4966

Sharing code between OS X (Objective-C) and iOS (Swift)

I have a Mac app written in Objective-C. Now I want to make a iOS version of it, written in Swift.

I followed the MVC model from the beginning.

I want to share the model code on both platforms. Now I ran into a problem that I can't solve. In a Objective-C model class, I use NSFont, which doesn't exist on iOS. Using UIFont gives me the error that it is unknown. UIKit is not available there.

What do I need to do that I can use AppKit and UIKit in one class?

Here I what I did:

#if TARGET_OS_IPHONE
UIFont* font;
#else 
NSFont* font;
#endif

Thanks for your help!

Upvotes: 2

Views: 350

Answers (2)

gnasher729
gnasher729

Reputation: 52538

Go through the WWDC videos. There is one video where Apple engineers explain what they did to have as much of code for Pages and Numbers common between MacOS and iOS. That should give you some ideas.

If you have a huge code base in Objective-C, I don't see any immediate advantage in changing it to Swift.

For the situation where you want a member to be either NSFont or UIFont, your approach doesn't work well at all. Much easier to have somewhere in a header file

#if TARGET_OS_IPHONE
typedef UIFont MyFont;
#else 
typedef NSFont MyFont;
#endif

to avoid having nothing but ifdefs in your code.

Upvotes: 2

Duncan C
Duncan C

Reputation: 131426

Short answer: You can't. You need to write conditionally compiled code that uses UIKit for iOS and AppKit for Mac OS.

Upvotes: 0

Related Questions