如何在Xcode中使用相同的共享代码创建多个应用程序?

Sle*_*lee 17 iphone xcode ipad ios

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

Ali*_*are 35

使用目标.这正是它们的用途.

在此处了解有关目标概念的更多信息.

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

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

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

-(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
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果您进一步向项目中添加文件,请小心将文件添加到两个目标,而不仅仅是活动文件:添加文件时,在出现的对话框中询问您是否要复制文件等,有一个目标列表和每个目标前面的复选框.(复选框状态已保存,因此您可能只需要检查一次) (4认同)
  • 如果您已经习惯了,可以将目标视为不同的 makefile。它们具有相同的作用。 (2认同)
  • 这是巨大的,谢谢.为了让它真正适合我,我需要做一个复制目标,然后更新目标设置,使用不同的Info.plist作为我的包名称等... (2认同)