【问题标题】:How to create multiple apps from same shared code in Xcode?如何从 Xcode 中的相同共享代码创建多个应用程序?
【发布时间】:2011-11-19 06:37:12
【问题描述】:

我正在开发 2 个不同的应用程序,它们共享 95% 的相同代码和视图。使用 Xcode 解决此问题的最佳方法是什么?

【问题讨论】:

    标签: iphone ios xcode ipad


    【解决方案1】:

    使用目标。这正是他们的目的。

    Learn more about the concept of targets here.

    通常,大多数项目都有一个 Target,对应一个产品/应用程序。如果您定义多个目标,您可以:

    • 在两个目标中包含一些(或全部)源代码文件,一些在一个目标中,一些在另一个目标中
    • 您可以使用 Build Settings 来使用不同的设置编译两个目标。

    例如,您可以为一个目标定义预编译器宏,为另一个目标定义其他宏(假设 OTHER_C_FLAGS = -DPREMIUM 在目标“PremiumVersion”中,OTHER_C_FLAGS = -DLITE 在“LiteVersion”目标中定义 LITE 宏),然后在您的源代码中包含类似的代码:

    -(IBAction)commonCodeToBothTargetsHere
    {
       ...
    }
    
    -(void)doStuffOnlyAvailableForPremiumVersion
    {
    #if PREMIUM
       // This code will only be compiled if the PREMIUM macro is defined
       // namely only when you compile the "PremiumVersion" target
       .... // do real stuff
    #else
       // This code will only be compiled if the PREMIUM macro is NOT defined
       // namely when you compile the "LiteVersion" target
    
       [[[[UIAlertView alloc] initWithTitle:@"Only for premium" 
           message:@"Sorry, this feature is reserved for premium users. Go buy the premium version on the AppStore!"
           delegate:self
           cancelButtonTitle:@"Doh!"
           otherButtonTitles:@"Go buy it!",nil]
       autorelease] show];
    #endif
    }
    
    -(void)otherCommonCodeToBothTargetsHere
    {
       ...
    }
    

    【讨论】:

    • 如果您习惯了,可以将目标视为不同的 makefile。它们具有相同的作用。
    • 这是巨大的,谢谢。为了让它真正适合我,我需要做一个复制目标,然后更新目标设置以使用不同的 Info.plist 作为我的包名称等...
    • 请注意,如果您进一步将文件添加到项目中,请注意将文件添加到两个目标,而不仅仅是活动目标:添加文件时,在出现询问您是否想要的对话框中要复制文件或不复制文件等,您在每个目标前面都有一个目标列表和复选框。 (复选框状态已保存,因此您可能只需要检查一次)
    猜你喜欢
    • 2011-05-30
    • 2012-01-03
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 2014-07-24
    • 2017-09-09
    • 2010-09-17
    • 2010-12-14
    相关资源
    最近更新 更多