Organize #import Statements for Objective-C/XCode - objective-c

After several months of coding in Objective-C, I completely understand when I need an #import, how import statements cascade (ripple?), and when to use forwarding classes. I do not know how to aggregate imports to get them inside of <> instead of in quotes (although maybe that's just for frameworks)...
The problem is that I'm making a huge mess. I come from Java (and the heavy-handed IDE), so I just add imports as I see fit. Sometimes I add them to the interface, but since that's usually not necessary, I just add them to the top of the .m in question.
Today I started thinking: there must be some rules of thumb on how to organize this stuff. In fact, since Objective-C is a C superset, there are rules of thumb for everything, but I don't know them. How should I organize my imports? Particularly:
When should I import in the .m?
When should I import in the .h?
Should I create .h files just for the sake of importing them (i.e., header files that just have imports in them)? If so, any hints on organizing that?
This is just a general idea of what I'm trying to figure out.

The <....> syntax is indeed just for frameworks. That doesn't mean you shouldn't create a framework to contain the core logic of your application though. Often this is a useful thing to do if you:
a) Need to provide support for loadable bundles that want to invoke aspects of your application logic (the bundle links to the framework, so does your application)
b) Write multiple apps that share the same core logic
Your question is somewhat subjective and you will get developers who argues both ways, but a convention I follow is:
Never import class definitions in the .h file, unless you are subclassing it. Use forward #class directives for everything in the .h.
Only import class definitions into a .m as you find you need to use that class in the implementation.
Generally speaking, the .h does not need access to the class definition of its ivars, method arguments or return values. It only needs to know that they are classes, which is what #class allows you to do. It does need access to the class definition of anything you're subclassing, adding a category to, or (obviously) implementing a protocol for.

Forget about whether <...> is for frameworks or what. <...> checks the system header search path, while "..." checks the current dir in addition to. One thing to remember however, is that the <CoreFoo/CoreFoo.h> declaration is handled a little differently on the apple platform, but only as it relates to apple frameworks: CoreFoo.framework/Headers/CoreFoo.h is matched to CoreFoo/CoreFoo.h

When imports are inside <> instead of quotes, all this means is that you are importing something from a framework. In fact, when doing this, the import is typically in the style
#import <Foundation/Foundation.h>
The first Foundation, before the slash, is the name of the framework in question, and the second one is just a header file in that framework. That header file is just something like
#import <Foundation/NSObjCRuntime.h>
#import <Foundation/NSArray.h>
#import <Foundation/NSAutoreleasePool.h>
...
#import <Foundation/NSURLHandle.h>
including every file from that framework. You can do this too, and isn't a bad idea for components that need multiple imports (although in that scenario, you may want a separate public interface)
For the other stuff, following the rule of thumb that you want stuff to know about as little as possible, you only want to put the import in the header file if it's necessary (like for an ivar or superclass) but really it's a matter of taste.

Related

What's a good place to put your module #imports?

So I am using the new #import module syntax introduced with the latest Xcode - I still wonder where the best place is to put them. Before, I would place library imports and very important categories in the .pch file, but now that's not necessary anymore (at least not for the native frameworks). My first idea was to create a modules.h file and do all the imports there, then include that modules.h file in the AppDelegate - but this doesn't seem right. Also, importing in the first place you need it doesn't make sense either, since you might use it in different places.
This is in fact a question about "best practices" which is - of course - a little subjective. But I think this affects a lot of people and the overall project structure. So please share your solution to this.
it sounds like you weren't doing it the best way before, In general you want as few symbols available at any one time. For a few different reasons:
less likely to make a mistake with symbols that have the same name but different values, or types... and for reasons that the compiler has to import less crap into each compilation unit.
I am not an expert on how #import has changed the compiler semantics of preprocessing and compiling, but I suspect you should still basically import things as close to the point that they will be used as possible.
I generally will not generally import any class's headers into another class's .h file.
in a .h I will forward declare any classes with #class SomeCLass and only include enough headers to satisfy the c/c++ types that I use as ivar/properties. The only exception to that being if I need to include a superclass's header or another .h for a protocol.
the rest of the includes go into the .m
I like to keep my pch pretty spartan, but if you have some utility categories or a widely used library you could include stuff in there, I tend not to... but in a smaller project you probably wont run into problems... you will run into indexing problems in projects with hundreds of source files, especially if you have some Objective-C++ units. That will end up hurting code completion and live syntax checking.

When to include the #import in the implementation file

Learning Objective-C and other c based Languages I learned that you should put the #includes and the #imports in the header file. And the #class goes there as well. Recently looking at example code from apple and other sources around the web the #class is in the header and all the imports are in the implementation file.
Which is correct? Are there reasons for both? Also why do you need to provide the #class declaration if you are importing the header file.
Neither case is "more correct", there are definitely reasons for both behaviours. For example, think about the case where you have two classes, each which has a reference to an object of the other type:
ClassA.h:
#interface ClassA : NSObject
{
ClassB *b;
}
ClassB.h:
#interface ClassB : NSObject
{
ClassA *a;
}
This code won't compile - you have a circular dependency in these headers. The solution is to forward declare the required classes using the #class directive.
A situation where you might prefer the #import directive in the header file might be if you have some common code besides just a class name that you care about in the other header - maybe C style functions or enumerated types or something.
Learning Objective-C and other c based Languages I learned that you should put the #includes and the #imports in the header file.
no - not in c based languages. you should put them in the implementation files where possible. you can't always create a zero-dependency header, but you should minimize it.
c based languages take a long time to compile, especially when the dependencies and includes are very complex, or there are unnecesary includes (introducing more dependency, coincidentally).
And the #class goes there as well. Recently looking at example code from apple and other sources around the web the #class is in the header and all the imports are in the implementation file. Which is correct?
use forward declarations (#class NAME;, #protocol NAME;, struct NAME, class NAME;`, etc.) wherever you can.
Are there reasons for both?
including in the header is the lazy way, it slows down your build times and introduces a lot of dependency. it's convenient because you don't have to write as many include/import declarations, but it's not considerate for people who must use your programs.
Also why do you need to provide the #class declaration if you are importing the header file.
if the class interface is already visible (has been included already, or another file has declared it), you do not need both . you'll need the interface visible if you intend to use the type (apart from some very trivial cases).
you certainly won't be excited to correct the mistake once your build times have grown slow -- it's best to learn and implement using the right approach. if you've not developed a complex c project, then you'd likely be very surprised to learn how much time is lost while compiling.
if you expect that your programs will never become nontrivial, and will be never shared or reused, then do whichever you prefer.
good luck!

Ability to specify more than one class declarations and definitions in objective-c interface and implementation sections respectively

I was just wondering if I have the option to specify more than one set of class declarations and definitions in the same file, without breaking it up into multiple files.
I'm guessing this is just the sign to break it up, but I was just wondering out of curiosity.
Also, bonus, when including, what is the difference between #include and #import.
Yes. The only really vital division is that a file should only be imported or compiled, not both — that is, unless all the code you feed to the compiler is in main.m, you need to have at least one header and one implementation file. The header can contain all the interface details for everything in your program and the implementation file can contain all the implementation details and it will work just like if you had separate files. You can just stack the contents of the would-be files end-to-end. That's actually what the #import and #include directives do — they literally copy the contents of the included file into the place where the directive is written.
Of course, what we're talking about here isn't a good design for a program at all.
Yes you can do that.
#import has built-in checks to prevent including the same file multiple times (avoiding stuff like #ifndef __MYHEADER_H...)
Yes you can have multiple classes in a same file but i don't prefer it. Its a good habit/good design to have classes in different files. Helps a lot in re-usability.
#import ensures that a file is only ever included once so that you never have a problem with recursive includes. I think performance may go down if use #include.

Including multiple classes in the same header file

I have an idea on how to do this, but I want to make sure I do it right....
I have five data classes. When I use one I typically use all of them (but not always).
Each class has a separate header file. I am getting sick of linking in each header file separately.
What is the best way resolve this issue?
Create a new header file called "DataFiles.h". Inside that, have your five #import statements. Then whenever you need the file classes, just #import "DataFiles.h".
Beware of circular dependencies.
(This is how Cocoa, Foundation, UIKit, CoreData, etc all behave. Notice that you just #import <Cocoa/Cocoa.h>, which imports everything else. Open up Cocoa.h and take a look)

Objective-C equivalent of Java packages?

What is the Objective-C equivalent of Java packages? How do you group and organize your classes in Objective-C?
Question 1: Objective-C equivalent of Java packages?
Objective-C doesn't have an equivalent to Java packages or C++ namespaces. Part of the reason for this is that Objective-C was originally a very thin runtime layer on top of C, and added objects to C with minimum fuss. Unfortunately for us now, naming conflicts are something we have to deal with when using Objective-C. You win some, you lose some...
One small clarification (although it's not much for consolation) is that Objective-C actually has two flat namespaces — one for classes and one for protocols (like Java's interfaces). This doesn't solve any class naming conflicts, but it does mean you can have a protocol and class with the same name (like <NSObject> and NSObject) where the latter usually adopts ("implements") the former. This feature can prevent "Foo / FooImpl" pattern rampant in Java, but sadly doesn't help with class conflicts.
Question 2: How to [name] and organize Objective-C classes?
Naming
The following rules are subjective, but they are decent guidelines for naming Objective-C classes.
If your code can't be run by other code (it's not a framework, plugin, etc. but an end-user application or tool) you only need to avoid conflicts with code you link against. Often, this means you can get away with no prefix at all, so long as the frameworks/plugins/bundles you use have proper namespaces.
If you're developing "componentized" code (like a framework, plugin, etc.) you should choose a prefix (hopefully one that's unique) and document your use of it someplace visible so others know to avoid potential conflicts. For example, the CocoaDev wiki "registry" is a de facto public forum for calling "dibs" on a prefix. However, if your code is something like a company-internal framework, you may be able to use a prefix that someone else already does, so long as you aren't using anything with that prefix.
Organization
Organizing source files on disk is something that many Cocoa developers unfortunately gloss over. When you create a new file in Xcode, the default location is the project directory, right beside your project file, etc. Personally, I put application source in source/, test code (OCUnit, etc.) in test/, all the resources (NIB/XIB files, Info.plist, images, etc.) in resources/, and so on. If you're developing a complex project, grouping source code in a hierarchy of directories based on functionality can be a good solution, too. In any case, a well-organized project directory makes it easier to find what you need.
Xcode really doesn't care where your files are located. The organization in the project sidebar is completely independent of disk location — it is a logical (not physical) grouping. You can organize however you like in the sidebar without affecting disk location, which is nice when your source is stored in version control. On the other hand, if you move the files around on disk, patching up Xcode references is manual and tedious, but can be done. It's easiest to create your organization from the get-go, and create files in the directory where they belong.
My Opinion
Although it could be nice to have a package/namespace mechanism, don't hold your breath for it to happen. Class conflicts are quite rare in practice, and are generally glaringly obvious when they happen. Namespaces are really a solution for a non-problem in Objective-C. (In addition, adding namespaces would obviate the need for workarounds like prefixes, but could introduce a lot more complexity in method invocation, etc.)
The more subtle and devious bugs come from method conflicts when methods are added and/or overridden, not only by subclasses, but also be categories, which can cause nasty errors, since the load order of categories is undefined (nondeterministic). Implementing categories is one of the sharpest edges of Objective-C, and should only be attempted if you know what you're doing, particularly for third-party code, and especially for Cocoa framework classes.
They use long names...
Article on coding style & naming in Cocoa / Objective-C
Discussion whether Obj-C needs namespaces (deleted, archive here)
See
What is the best way to solve an Objective-C namespace collision?
for a discussion of how Objective-C has no namespaces, and the painful hacks this necessitates.
Unfortuantely objective c doesn't have any equivalent to namespace of C#,c++ and package of java....
The naming collisions could be solved by giving contextual name for example if u gonna give a name to method it should imply the class and module that it comes in so that...these problems could be avoided.
Go through the following url to know more on naming convention as advised by apple
http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/ProgrammingWithObjectiveC/Conventions/Conventions.html
What about something like this (inside a directory)?
#define PruebaPaquete ar_com_oxenstudio_paq1_PruebaPaquete
#interface ar_com_oxenstudio_paq1_PruebaPaquete : NSObject {
and importing it like this:
#import "ar/com/oxenstudio/paq1/PruebaPaquete.h"
PruebaPaquete *p = [[PruebaPaquete alloc] init];
and when you have name collision:
#import "ar/com/oxenstudio/paq1/PruebaPaquete.h"
#import "ar/com/oxenstudio/paq2/PruebaPaquete.h"
ar_com_oxenstudio_paq1_PruebaPaquete *p = [[ar_com_oxenstudio_paq1_PruebaPaquete alloc] init];
ar_com_oxenstudio_paq2_PruebaPaquete *p2 = [[ar_com_oxenstudio_paq2_PruebaPaquete alloc] init];
Well, I think all the other answers here seem to focus on naming collisions, but missed at least one important feature, package private access control that java package provides.
When I design a class, I find it is quite often that I just want some specific class(es) to call its methods, b/c they work together to achieve a task, but I don't want all the other unrelated classes to call those methods. That is where java package access control comes in handy, so I can group the related classes into a packaged and make those methods package private access control. But there is no way to do that in objective c.
Without package private access control I find it is very hard to avoid people writing code like this, [[[[[a m1] m2] m3] m4] m5] or [a.b.c.d m1].
Update: Xcode 4.4 introduced "An Objective-C class extension header", in my opinion, that is in some way to provide "package private access control", so if you include the extension header, you can call my "package private" methods; if you only include my public header, you can only call my public API.