How to manage the code of multiple, very similar Xcode projects - objective-c

Greetings Stackoverflow Community,
I have taken on the task of 'unifying' 4 mobile iPhone apps that share 95% of the code and differ only in 5% (this is somewhat of an over-simplification, but never mind). Each of the apps has its own hefty set of resources (media files).
After 'unifying' the 4 apps, I will be adding new functionality to the apps, mostly functionality that the apps will share.
I would appreciate hearing your opinions on what's the best way to manage the code of these apps. Here is the approach I'm taking at the moment.
I'm maintaining only one Xcode project which includes the functionality of all 4 apps. The functionality that is not shared among all apps is enclosed in a condition such as: if (appName == 'X')...
Each app has its own info.plist file, so I have 4 of such files: infoX.plist, infoY.plist, ...
Before I build an app, two things are done:
a. in the Build Settings, I specify the name of info.plist to use.
b. I ensure that only the app's resources (media files) are in the project. I delete the other apps' resources.
As the apps are 95% similar in their code, having only "One App to Rule Them All" ensures that when the code gets upgraded, all apps enjoy the upgrade. You can assume that the apps will remain very similar in their code.
As the apps' media files are large and many, I'm keeping them off the Git repository.
How does this all sound?
Many thanks!

There are better ways:
A. Move to framework
It depends on how generic are common parts of the apps. But you should think about putting parts of it in a separate project that is a framework. You can link your 4 apps against that framework. But, of course, not everything will go there.
B. Have different targets
For sure you should have 4 different targets. Xcode let you set build settings for each setting commonly per project or specially per target. Additionally you can customize the build phases (including copy of the media files) on a per target base. So you do not have to rename or delete and insert anything. You simply select a target, you want to build.
C. Project tree
Xcode allows you to have subprojects with common code. Maybe things like common "foundation" classes of your app. You can have different projects for each app in a single workspace, all using the subproject.
Probably the best way is a combination, depending on what is the subject. However I would start with B. and likely add the other techniques, if needed.

I encountered more or less the same case, and we decided to use one Xcode project with multiple targets. That way you can simply change the target before hitting the build button (or configure specific build scripts changing the target). In our project, we had a few files sharing the same names (in different folders), and associated each one with a different target. For example, we had three "Stylesheet.h/.m" with different UIColor & UIFont definitions stored in different folders, and each one of them was linked to a different target. Same thing for the "Localizable.strings".

Related

Build multiple apps with same core

I have few separate apps that have absolute same logic and functions but have different icons and some design elements. The problem is that when some changes to logic and functions are made - I need to manually add this functionality to all apps and after this - I need to resubmit each app.
Maybe there is some way to separate all logic so I need to change it only in one place, and all my apps would get it?
In my opinion the neatest solution is to have one codebase with multiple targets. Yes you still have to resubmit each app when you change some code, but you would have to do that anyway would you not?
You can pick one of your apps to convert to your 'main' codebase.
E.g. Pick app one and duplicate the target multiple times:
You will want to change your scheme names after doing this:
You can set the bundle identifier and deployment info separately for each app just as you did before, and icon sets:
To differentiate between your apps in code you can use compiler flags (Target -> Build settings - Other swift flags) :
You can then do something like this in your code:
#if APP_ONE
...
#else
...
#endif
One solution (though not necessarily the best) is to have a single code base. I.e. you have only one physical copy of each of your classes. All your code files are located in a folder of one of the projects and the other projects use those files as well. It's just a matter of setting paths.
In this structure when you change or add some code in one of the projects (and doesn't really matter which one), all the projects are updated.
The image catalogs are different for each project.
The disadvantages of this approach are that you still need to build and submit each app separately and when adding a new class you need manually to add it to all the projects. Otherwise they won't compile.
The advantages are that when building an app, you build only one app and not all together (less time). It's also easy to manage changes to a specific app - you can just add some extension with additional functionality to only one project - the rest won't need it.

Build Multiple iOS Apps out of a Framework

I have a project where I need to build some apps out of one Basic App.
For "Sub-Apps" it changes the API-Credentials, Fonts, Sizes, Colors and some features of the App.
So I changed my App that I can easily add features, change colors, ... by changing simple String constants to build new Apps faster.
I thought that the best solution would be to add multiple Targets to this XCode Project and set the individual Settings of the App with Conditional Compiler flags
#ifdef AppTarget1
qr_reader = YES;
#endif
But the Problem is, that in future will be available multiple versions of the Framework. So when updating an App based on a old Framework we always had to do the adjustments to work with the new Version of the framework (if any) and we've no control over the Framework Versions, ect.
One goal is also to allow our Developers with a Simple Podfile build new Apps easily.
So the next idea was to create a Framework Project, what then is included with CocoaPods in our Main Apps. I followed this tutorial: http://chariotsolutions.com/blog/post/using-cocoapods-to-manage-private-libraries/
In the MainApp I included the Framework, the MainApp-AppDelegate Class is a Subclass of the Framework-AppDelegate Class.
#interface MainApp_AppDelegate : FrameworkAppDelegate
The Method where I set all the App-Based Settings I overwrite in the MainApp_AppDelegate.
#implementation MainApp_AppDelegate
-(void)initSettings {
qr_reader = YES;
}
#end
It worked like a charm, but one Problem I've with images. The AppFramework contains Image training.png and image y.png.
In the Main App xyz I decide that the Image training.png looks not good for this App, so I want to change only that (y.png I want the version included in the Framework). I put the x.png into the Main App Ressources Folder, but after compiling and Running there I see the Image included in the AppFramework Project.
Are there any ways to change that behaviour or better ways to create a Framework?
What is happening is Cocoapods copies its resources in the final .app bundle after your app is done copying his. So your training.jpg gets overwritten by your framework's.
Build phases order
As #masam said, you need to reorder the build phases of your project in order to copy your app's resources after Cocoapods' resources.
(Notice how "Copy Bundle Resources" is now under "Copy Pods Resources" in the list)
Force resources copy
Unfortunately, this will not be sufficient, as Xcode's build system is (tries to be?) smart and will not copy (or recompile in the case of a source file) a target which is "up-to-date". For a static resource like an image, being up-to-date means that the target path (in the final .app bundle) is newer than the source path (in you Xcode project).
So if you try to run your app now, you will notice no change. Xcode won't copy the training.jpg as it is already present and newer in the .app.
You will need to trick Xcode into thinking that the resources in the .app are outdated and needs to be updated. To do this, add a new "Run Script Build Phase" between "Copy Pods Resources" and "Copy Bundle Resources":
The script should set the modification date of the resources to an earlier date, to force Xcode to copy your app's resources. touch does the job:
find ${TARGET_BUILD_DIR} -name 'training.jpg' -exec touch -ct $(date -v-1d "+%Y%m%d%H%M.%S") {} \;
We use date -v-1d "+%Y%m%d%H%M.%S" to set the resource's modification date to yesterday.
Xcode will now overwrite the framework's image with the app's one.
Manage the targets resources
Again, as #masam said, don't forget to add the resource only to correct targets.
eg.
Here, the app image will be used in DummyApp, but DummyApp2 will use the framework image.
Conclusion
tl;dr: Avoid this if possible.
For a newcomer on your project, this is impossible at first glance to know why some targets build with one file and not the other;
Depending on the kind of resources of the framework you want to override, you will probably need to maintain the "Reset Resources Modification Time" script (probably by making find more inclusive, eg. find ${TARGET_BUILD_DIR} -name '*.png');
More of a subjective opinion: I'd recommend against hiding resources from the framework with your owns.
On the one-target-per-app-flavor thingy:
Remember that each modification you make on one target's Build Phases will NOT impact other targets Build Phases. You'll need to edit every targets individually. Hence my previous don't do it if you can avoid it.
I perfectly understand the need to have multiple targets to build multiples apps based on the same codebase, but Xcode is horribly bad at managing a large number of targets. Take it from a guy currently working on an fairly large app (1k+ files, and a lot of dependencies) with 65 different targets: this is a nightmare.
The .pbxproj will basically grow in factor of your number of targets (25MB in my case), and you'll get the beach ball each time a project modification in done in Xcode. And as each target is managed independently, each time you need to eg. add/remove a compile flag, you will need to update each target, one. by. one. (or you will edit the .pbxproj "by hand" with sed/awk/whatever, which is faster, but risky... but fun :)).
Oh... and did I mention merge conflicts?
This might be due to a certain order in your build phases (Project -> Build Phases). Default, it will copy the bundle resources first and then copy Pods resources (overwriting the resources you had in your main application).
You could change the order of "Copy Pods Resources" to an earlier phase by dragging it to above "Copy Bundle Resources".
You also have to verify that the image resource included in your main project, has a correct target membership, by clicking on the image resource -> file inspector -> target membership. It should be checked for the target you are compiling.
duplicate your targets !?
The last apps I build by this way were using a different bundle identifier for each target.
Then just have a test to you bundle ID to make your different settings programmatically.
NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];

Best way to share code between multiple projects in iOS

We're planning to launch a serie of applications in AppStore. They will be for some kind of different journals, showing different contents downloaded from a server via XML. So these applications will be made from exactly the same code (It's an universal application, so It'll work both in iPhone/iPad).
My initial idea was, in order to upload the application, compile just changing the images, logos and configurations (plist) that makes the application react as a particular journal. The compressed file would be uploaded to the AppStore.
However, this has resulted a horrible method, which promotes failures and mistakes. If I forget to change some image, as you can't see them in the compiled file (as it is included) they will end up in the store (and I will need four or five days in order to get the application changed).
I'm trying to look up for a better approach, wich keep the projects as independent as possible. I would like to be able to share the entire codebase: views, classes and nibs and create different projects for every journal.
Which is the best method to achieve that?. What structure would let me group both logic (controllers, classes) and UI and use it in the different projects?.
I hope I've explained.
As always, thank you very much.
You should keep most of your common code as a library project. Each final project should link with this project and provide images/assets along with code to mention these assets to common code. In my day job, I write a common library too, which gets used by 2 products/apps at my employer.
An Xcode project can have multiple Targets, all the Targets sharing code, but each Target getting its own resources (icons, images, text, plists, etc.) from a different subdirectory/folder within the same project directory/folder. Then you can check the whole thing, or just the shared source, into your source control repository.
You should also be testing each of your apps, built exactly the same way as any submission except for the codesigning, on a device before uploading to the store.
You can have a single Xcode project that creates multiple applications. You'll need to create a separate Info.plist with a different bundle identifier for each app.
If you are using a git repository you can just branch for each different app you want and that would keep track of all the differences and if you need to switch which you are working on you just have to checkout that branch. This would allow for the exact same structure just minor differences between the actual code for each.

What is the best way to organize source code of a large Cocoa application in Xcode?

Here is what I'm looking for:
I'd like to separate pieces of functionality into modules or components of some sort to limit visibility of other classes to prevent that each class has access to every other class which over time results in spaghetti code.
In Java & Eclipse, for example, I would use packages and put each package into a separate project with a clearly defined dependency structure.
Things I have considered:
Using separate folders for source files and using Groups in Xcode:
Pros: simple to do, almost no Xcode configuration needed
Cons: no compile-time separation of functionality, i.e. access to everything is only one #import statement away
Using Frameworks:
Pros: Framework code cannot access access classes outside of framework. This enforces encapsulation and keeps things separate
Cons: Code management is cumbersome if you work on multiple Frameworks at the same time. Each Framework is a separate Xcode project with a separate window
Using Plugins:
Pros: Similar to Frameworks, Plugin code can't access code of other plugins. Clean separation at compile-time. Plugin source can be part of the same Xcode project.
Cons: Not sure. This may be the way to go...
Based on your experience, what would you choose to keep things separate while being able to edit all sources in the same project?
Edit:
I'm targeting Mac OS X
I'm really looking for a solution to enforce separation at compile time
By plugins I mean Cocoa bundles (http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/LoadingCode/Concepts/Plugins.html)
I have worked on some good-sized Mac projects (>2M SLOC in my last one in 90 xcodeproj files) and here are my thoughts on managing them:
Avoid dynamic loads like Frameworks, Bundles, or dylibs unless you are actually sharing the binaries between groups. These tend to create more complexity than they solve in my experience. Plus they don't port easily to iOS, which means maintaining multiple approaches. Worst, having lots of dynamic libraries increases the likelihood of including the same symbols twice, leading to all kinds of crazy bugs. This happens when you directly include some "helper" class directly in more than one library. If it includes a global variable, the bugs are awesome as different threads use different instances of the global.
Static libraries are the best choice in many if not most cases. They resolve everything at build time, allowing code stripping in your C/C++ and other optimizations not possible in dynamic libraries. They get rid of "hey, it loads on my system but not the customer's" (when you use the wrong value for the framework path). No need to deal with slides when computing line numbers from crash stacks. They catch duplicate symbols at build time, saving many hours of debugging pain.
Separate major components into separate xcodeproj. Really think about what "major" means here, though. My 90-project product was way too many. Just doing dependency checking can become a very non-trivial exercise. (Xcode 4 can improve this, but I left the project before we ever were able to get Xcode 4 to reliably build it, so I don't know how well it did in the end.)
Separate public from private headers. You can do this with static libs just as well as you can with Frameworks. Put the public headers in a different directory. I recommend each component have its own public include directory for this purpose.
Do not copy headers. Include them directly from the public include directory for the component. Copying headers into a shared tree seems like a great idea until you do it. Then you find that you're editing the copy rather than the real one, or you're editing the real one, but not actually copying it. In any case, it makes development a headache.
Use xcconfig files, not the build pane. The build pane will drive you crazy in these kinds of big projects. Mine tend to have lines like this:
common="../../common"
foo="$(common)/foo"
HEADER_SEARCH_PATHS = $(inherited) $(foo)/include
Within your public header path, include your own bundle name. In the example above, the path to the main header would be common/foo/include/foo/foo.h. The extra level seems a pain, but it's a real win when you import. You then always import like this: #import <foo/foo.h>. Keeps everything very clean. Don't use double-quotes to import public headers. Only use double-quotes to import private headers in your own component.
I haven't decided the best way for Xcode 4, but in Xcode 3, you should always link your own static libraries by adding the project as a subproject and dragging the ".a" target into your link step. Doing it this way ensures that you'll link the one built for the current platform and configuration. My really huge projects haven't been able to convert to Xcode 4 yet, so I don't have a strong opinion yet on the best way there.
Avoid searching for custom libraries (the -L and -l flags at the link step). If you build the library as part of the project, then use the advice above. If you pre-build it, then add the full path in LD_FLAGS. Searching for libraries includes some surprising algorithms and makes the whole thing hard to understand. Never drop a pre-built library into your link step. If you drop a pre-built libssl.a into your link step, it actually adds a -L parameter for the path and then adds -lssl. Under default search rules, even though you show libssl.a in your build pane, you'll actually link to the system libssl.so. Deleting the library will remove the -l but not the -L so you can wind up with bizarre search paths. (I hate the build pane.) Do it this way instead in xcconfig:
LD_FLAGS = "$(openssl)/lib/libssl.a"
If you have stable code that is shared between several projects, and while developing those projects you're never going to mess with this code (and don't want the source code available), then a Framework can be a reasonable approach. If you need plugins to avoid loading large amounts of unnecessary code (and you really won't load that code in most cases), then bundles may be reasonable. But in the majority of cases for application developers, one large executable linked together from static libraries is the best approach IMO. Shared libraries and frameworks only make sense if they're actually shared at runtime.
My suggestion would be:
Use Frameworks. They're the most easily reusable build artifact of the options you list, and the way you describe the structure of what you are trying to achieve sounds very much like creating a set of Frameworks.
Use a separate project for each Framework. You'll never be able to get the compiler to enforce the kind of access restrictions you want if everything is dumped into a single project. And if you can't get the compiler to enforce it, then good luck getting your developers to do so.
Upgrade to XCode4 (if you haven't already). This will allow you to work on multiple projects in a single window (pretty much like how Eclipse does it), without intermingling the projects. This pretty much eliminates the cons you listed under the Frameworks option.
And if you are targeting iOS, I very strongly recommend that you build real frameworks as opposed to the fake ones that you get by using the bundle-hack method, if you aren't building real frameworks already.
I've managed to keep my sanity working on my project which has grown over the past months to fairly large (number of classes) by forcing myself to practice Model-View-Control (MVC) diligently, plus a healthy amount of comments, and the indispensable source control (subversion, then git).
In general, I observe the following:
"Model" Classes that serialize data (doesn't matter from where, and including app's 'state') in an Objective-C 1 class subclassed from NSObject or custom "model" classes that inherits from NSObject. I chose Objective-C 1.0 more for compatibility as it's the lowest common denominator and I didn't want to be stuck in the future writing "model" classes from scratch because of dependency of Objective-C 2.0 features.
View Classes are in XIB with the XIB version set to support the oldest toolchain I need to support (so I can use a previous version Xode 3 in addition to Xcode 4). I tend to start with Apple provided Cocoa Touch API and frameworks to benefit from any optimization/enhancement Apple may introduce as these APIs evolve.
Controller Classes contain usual code that manages display/animation of views (programmatically as well as from XIBs) and data serialization of data from "model" classes.
If I find myself reusing a class a few times, I'd explore refactoring the code and optimizing (measured using Instruments) into what I call "utility" classes, or as protocols.
Hope this helps, and good luck.
This depends largely on your situation and your own specific preferences.
If you're coding "proper" object-oriented classes then you will have a class structure with methods and variables hidden from other classes where necessary. Unless your project is huge and built of hundreds of different distinguishable modules then its probably sufficient to just group classes and resources into folders/groups in XCode and work with it that way.
If you've really got a huuge project with easily distinguishable modules then by all means create a framework. I would suggest though that this would only really be necessary where you are using the same code in different applications, in which case creating a framework/extra project would be a good way to effectively copy code between projects. In practically all other cases it would probably just be overkill and much more complicated than needed.
Your last idea seems to be a mix of the first two. Plugins (as I understand you are describing - tell me if I'm wrong) are just separated classes in the same project? This is probably the best way, and should be done (to an extent) in any case. If you are creating functionality to draw graphs (for example) you should section off a new folder/group and start your classes and functionality within that, only including those classes into your main application where necessary.
Let me put it this way. There's no reason to go over the top... but, even if just for your own sanity - or the maintainability of your code - you should always endeavour to group everything up into descriptive groups/folders.

Dividing a project into multiple Xcode project files

An iPad project I have been working on has become bloated with a huge number of files. The application is a prototype and we are considering ways to prevent this when we rewrite it.
One of the members of our team suggests dividing all of the components into separate Xcode projects which will be included in a master Xcode project.
Is this a good idea? What are the reasons, if any, to avoid dividing features/components/controls into separate Xcode projects?
You can add a subsidiary project file to a master project file in Xcode. Just choose "Add File" and add it. When Xcode builds the master it will build the subsidiary as well if needed.
I use a similar system. I often break a project into sub projects just so I can focus on and enforce encapsulation. I write the data model first, then add the app delegate, then specific UI elements. I add each project to the next in turn. This also allows me to go back and change things without as much risk of breaking.
Really, a properly designed objective-c app should be easy to decompose into multiple project. Ideally, all the components are so encapsulate that they don't need any others save the data model.
We have put some of the code in its own project, building a framework which we link against at some of the other projects. It's sometimes annoying that you won't see the implementation files of the framework code right away in another project (by cmd+clicking or cmd+shift+D, or whatever you do normally to navigate). Xcode will only show you the header, you'll have to open the other project and find your file there manually. Not a big deal, but if you look up the code often, it will bother you.
A real problem is that you change the scope of some operations. Stuff like "Find in project" will work on a different file set, which might not be what you want sometimes (trying to find where this method is called / key is used in your whole code, or something); well, there remains Finder / find, so it might be okay. Refactoring is not - all the renaming stuff just breaks, as it will change only the code of the current project, but not of projects referencing this one. If you change interfaces often, better avoid splitting up the project.
A good thing is that you will get less conflicts on your .xcodeproj files (if stored in a shared repository) as someone removing a file from project X won't create a conflict with someone else adding a target on project Y, which where previously the same .xcodeproj (not exactly sure this is a conflict case, but there definitely are some).
Now with Xcode4 you can create a workspace and add all your projects there. Only for documentation purpose :)
To view and modify subproject implementation files, you should add the sub projects directly into the main project.
1 step - Drag and drop the .xcode project files to main project.
2 step - Go to main project TARGETS - > Build Phases. Add subproject target in Target Dependencies. You can also add binary files in Link Binary With Libraries.
3 step - Add subproject source path to main projects header search path.
Go to main project - > Build Settings - > Header Search Paths (e.g $(SRCROOT)/../CoconutKit-master/CoconutKit/Sources )
An Xcode project can have any number of build targets within it, and you can arbitrarily group source files into folders. What makes you think that multiple projects are necessary?