Objective-C #import loop - objective-c

I have the following code:
#import <Foundation/Foundation.h>
#import "ServerRequest.h" // works even though this line is included
#import "ServerResponseRecord.h"
#protocol ServerRequestDelegate<NSObject>
-(void)request:(id)request gotResponseRecord:(ServerResponseRecord*)response;
-(void)request:(id)request gotError:(NSError*)error;
#end
It compiles and runs fine. However, if I replace the method declarations with:
-(void)request:(ServerRequest*)request gotResponseRecord:(ServerResponseRecord*)response;
-(void)request:(ServerRequest*)request gotError:(NSError*)error;
I get the unexpected syntax error "error: expected ')' before 'ServerRequest'". The only reason I can think this might be a problem is that ServerRequestDelegate.h and ServerRequest.h #import each other. However, I don't understand why the code works with the #import line with (id)request. I also don't understand why it's a syntax error.
Can someone provide a good explanation?

You've already hinted at the explanation: an #import cycle.
The first thing I'd do is remove the #include and add the following line above the #protocol definition:
#class ServerRequest;
This is a forward class declaration, and can help break the import loop. Check out this SO question for more details. Apple also has a brief explanation in this guide.
Basically, #import'ing a file causes the compiler to bring the entire text of that file into the file in question, and although #import is "smarter" than #include, it doesn't mean you're immune from import errors. The #class declaration is a way to tell the compiler that a class exists without importing the header. It's appropriate to use when you only need to know about the class name, but don't care about the methods it provides. Generally, you want to use #class in the .h file and #import in the .m file, where you're actually interacting with the class.

#import "loops" are not a problem. #import is the same as #include except that it tracks files and makes sure the preprocessor only reads them in the first time.
Usually when you get an error like that it is due to a problem in the included file. So the error is probably in ServerResponseRecord.h, thought it is probably being tripped by actually using the object declared by it. Without seeing the complete headers it is not possible to say exactly what is going on.

Related

Nested #import statements: how to hide nested ones?

I have the following project structure:
Main.h
Son1.h
Son2.h
They're not related (no father/son relationships), just two imports, like in Main.h I have:
#import Son1.h
#import Son2.h
If, from another file I write
#import Main.h
I will see all the methods/properties of Main.h (and that's ok) but I will also see the methods of Son1.h and Son2.h.
How can I prevent this?
It's important to understand what #import (and the C version: #include) do.
Compilation of C programs conceptually have 3 steps:
Preprocessing
Compiling
Linking
The directives beginning with # are acted on by the preprocessor (it doesn't matter at all whether this is a separate binary or part of the compiler). Both of these statements cause the contents of the named file to inserted into the importing (or including) file at the point where the directive is found. This is completely language-agnostic. The imported file can have anything in it. You can import a JPG, if you want (but good luck compiling!).
In your example, by importing Son1.h and Son2.h in Main.h, you are creating, from the compiler's perspective, a single file with the contents of Son1.h followed by the contents of Son2.h followed by whatever is in Main.h itself. At this level, the idea of hiding content doesn't make sense. You explicitly asked the preprocessor to put those contents there. It doesn't know anything about the text it's inserting, so it can't follow any kind of Objective-C directive, even if such existed.
The comments are getting to another point. Importing in a .h should be kept to an absolute minimum. The most common reasons to import are for class and protocol type definitions, and Objective-C allows you to forward declare both of these precisely to avoid otherwise necessary imports.
If you have something like:
#interface MyClass : NSObject
#property(nonatomic, strong) MyOtherClass *myOtherClass;
#end
You normally would have to #import "MyOtherClass.h". However, with forward declarations, you can do this instead:
#class MyOtherClass;
And move the #import to the implementation file, which is generally hidden from other files.

Having compilation error with #import

I'm having some error on the following relationship
I have 2 classes, Class A and Class B
inside Class A header, it will #import "B.h"
inside Class B header, it will #import "A.h"
I'm having error during compilation. Anyone know how can I resolve this?
Error looks something like this:
expected specifier-qualifier-list before 'GameUILayer'
Instead of importing the headers in the .h files, use forward declarations. So instead of
#import "ClassA.h"
you use:
#class ClassA
etc
and then you use the import statement within the .m files.
See my earlier answer for the link to the documenation.
You're creating a circular dependency. One class should import the other. They can't both import each other. If you're making interacting classes like that, there should be a hierarchy of dependence. B depends on A, A depends on, at a minimum, the root class NSObject. If you make two classes dependent on each other, the compiler can either yell at you or try to compile it and end up running around in circles. Most compilers are designed to yell at you.

missing #end + expected identifier "{" errors in XCode 4.2 .h module

I can't get rid of two errors on my class module, even when I have simplified the code to the minimum expression:
#import <Foundation/Foundation.h>
#interface MyClass : NSObject
#end
Both errors are reported on the #interface line, and they are:
- missing #end
- expected identifier or '{'
Check the header files that are #imported on the same page, and verify that the headers have matching #interface/#end statements.
I had the same problem, and XCode reported that my .m file's #implementation had a missing #end statement, even when I pared it down to just:
#import "MasterViewController.h"
#import "MyBadHeaderFile.h"
#implementation MasterViewController
#end
In reality the bug was a missing #end from a #imported MyBadHeaderFile.h file.
I had a similar problem found adding a } in my code got rid of the errors for me.
Before I added the } I was getting the following errors:
unexpected # in program (parse issue)
Expected } (parse issue)
#end is missing in implementation context (semantic issue)
rokjarc's comment should be a correct answer:
1) compiler can point you to completely wrong file. go trough all .h and .m files in your project and check for matching '#interface'/'#end', '#implementation'/'#end' and so on.
2) it happens also if you by mistake import .m file instead of .h
It doesnt matter in which file the error is appearing. Make sure to check for all the files you have recently modified. I appeared to have copied a file from test project to my actual project and forgot #end in one of the files. It gave me error on totally unrelated .h file.
Try to remove the implementation file of this class from "Compile sources in project settings"
#interface MyClass : NSObject{
}
#end
I experienced a similar issue, the code was fine but it was throwing this error.
I eventually resolved it by cleaning the project, have you tried that?
PEBKAC + Lack of Specificity in the Static Analyzer Strings
The existing answers are certainly useful. I just want to add a common PEBKAC that causes this; as well as highlight that CLANG should be clearer here. Someone with domain knowledge should file a patch to make the error message clearer. The \n#end\n part of the message is ridiculous no matter what.
(Showing line breaks as \n in a message designed to help users of a
GUI? Really CLANG?)
The Cause
When you have just created a new Class, the #interface & #implementation files look extremely similar, and Xcode will automatically place your cursor in the implementation.
If you thoughtlessly begin typing out your interface (your method signature declarations) in the implementation file, you'll end up with this warning because the analyzer sees methods without opening and closing braces.
A visual example, shown forthwith
I had the same error ,and it was because i had
#interface MyViewController ()
declared two times in the MyViewController.m

Strange behavior with compile error "expected specifier-qualifier list before 'CustomClass'"

I have been having some trouble lately with using custom classes as types. As described in the title, I have been getting compile errors similar to the one below:
expected specifier-qualifier list before 'MyClass'
My code is usually something along the lines of this:
#interface MyCoolClass : NSObject {
MyClass *myClassObject; // Error is on this line.
}
I also occasionally use something like this:
#interface MyCoolClass : NSObject {
IBOutlet MyClass *myClassObject; // Error again on this line
}
Im not really sure if that is good to use but on occasion, I have done something like that so I could connect my objects together with Interface Builder so that one object could invoke a method on another object.
I've been able to do this before successfully with other projects but when I tried to do it today, it gave me this error. Any ideas what could be causing it? As far as I can tell, I have done the same thing that I did in the other project here.
It is also to my understanding that this error usually gets thrown if the type is not defined, but I am pretty sure that I have defined it.
Oh, GCC how obtuse and opaque can your errors possibly be....
Try compiling with the LLVM 2.0 compiler. It'll give you much more sane errors.
In this case, what is usually going on is that the compiler doesn't have a clue what MyClass is or there is a syntax error in the previously included header file that doesn't cause a compilation error until the #interface is hit in the file spewing the error.
It could also be a misspelling.
Or, as suggested, you need to #import "MyClass.h" into the header file (or implementation file or, even better, the PCH file) so that MyClass is defined before the iVar declaration.
#class MyClass;
That'll also do the trick.

What is the difference between #class and #import

When I compile with the following code there are no errors:
#class RootViewController;
//#import "RootViewController.h"
When I compile with the following code I get an error:
//#class RootViewController;
#import "RootViewController.h"
"error: expected specifier-qualifier-list before 'RootViewController'"
I don't understand what the difference is between the two because I used #import in a similar class and it compiled without errors!
#class is used when you need to know the name of a class in a particular file, but you don't need to know any details about the class (its methods, for example). #import is used when you actually need to use the class (i.e., send it a message).
For example, if you're declaring instance variables in a header file, you can use #class to declare an instance variable of a certain type:
#class MyOtherClass;
#interface MyClass : NSObject
{
MyOtherClass *myIvar;
}
#end
Since you're not using myIvar yet, you don't need to know anything about it except that the type MyOtherClass exists.
However:
#import "MyOtherClass.h"
- (void)doSomething
{
[myIvar doSomethingElse];
}
In this case, you're sending the doSomethingElse message to myIvar; the compiler needs to know that instances of MyOtherClass define this method, so you have to import the header file or the compiler will complain.
Why worry about this?
It mostly has to do with dependencies. When you #import file A into file B, file B becomes dependent upon file A -- that is, if file A changes, you'll have to recompile file B. If you use #class in file B, file B is not dependent on file A, and thus doesn't need to be recompiled when file A changes -- so if you're just declaring a type and not actually dependent upon the implementation of file A, you can save yourself compilation time by not #importing file A.
I decided to refer to the documentation because I was still confused:
#import
This directive is identical to #include, except that it makes sure that the same file is never included more than once. It’s therefore preferred and is used in place of #include in code examples throughout Objective-C–based documentation.
This convention means that every interface file includes, indirectly, the interface files for all inherited classes. When a source module imports a class interface, it gets interfaces for the entire inheritance hierarchy that the class is built upon.
#class
Declarations like this simply use the class name as a type and don’t depend on any details of the class interface (its methods and instance variables), the #class directive gives the compiler sufficient forewarning of what to expect. However, where the interface to a class is actually used (instances created, messages sent), the class interface must be imported.
http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocDefiningClasses.html#//apple_ref/doc/uid/TP30001163-CH12-TPXREF123
Basic rule: use #class in you header file and #import in your implementation file.
(However, you need to #import your class' superclass. And in some other circumstances you also need to use `#import" in the header.)
#import is not equivalent to #include. If a file is included many times, it will be loaded each time, but with many #imports of the same file, it will still only be loaded once.
Therefore, the main reason to use #class is not to avoid circular dependencies, but to make compilation faster.
Here's an example of when you must use #class
//MYControl.h
#class MYControl; // Must use class
#protocol MYControlDelegate
-(void)control:(MYControl *)control didChangeToState:(UIControlState)state;
#end
#interface MYControl : UIControl
{
id<MYControlDelegate> delegate_;
}
#property (nonatomic, assign) id<MYControlDelegate> delegate;
#end
//MYControl.m
#implementation MYControl
#synthesize delegate = delegate_;
. . .
In this case, there is nothing to import, because the delegate protocol is declared above the main class in the header file. But you still need to be able to refer to the main class which has not yet been declared. So what #class does is to just let the compiler know that there is some class that is called MYControl and will be defined at some point. (Not at runtime however. The class will be defined in the course of the compilation.)
EDIT: From the Objective-C manual:
Since declarations like this simply
use the class name as a type and don’t
depend on any details of the class
interface (its methods and instance
variables), the #class directive gives
the compiler sufficient forewarning of
what to expect. However, where the
interface to a class is actually used
(instances created, messages sent),
the class interface must be imported.
Typically, an interface file uses
#class to declare classes, and the
corresponding implementation file
imports their interfaces (since it
will need to create instances of those
classes or send them messages).
The #class directive minimizes the
amount of code seen by the compiler
and linker, and is therefore the
simplest way to give a forward
declaration of a class name. Being
simple, it avoids potential problems
that may come with importing files
that import still other files. For
example, if one class declares a
statically typed instance variable of
another class, and their two interface
files import each other, neither class
may compile correctly.
Note that circularity is mentioned in the last sentence as one in a general class of issues dealt with by using #class.
#class is used to avoid circular dependency... This prevents circular references where in one header A imports a second header B which(B) imports the first(A) which imports the second (B)and so on in an endless cycle....#class is generally used to ask compiler to look for its definition at runtime... especially when it resides in some static library..
Other than that #import works
See this question
#class:- It defines that you can create instance variable of the imported class and use it in your class.
import:- It defines that you can access the variables declared in the required imported class.
you can use given link for more info.
http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocDefiningClasses.html#//apple_ref/doc/uid/TP30001163-CH12-TPXREF123
#class means that the definition of the class RootViewController is not yet declared, but will be defined at run time. I believe it is like declaring an extern class in c++.
#import is equivalent to #include.
by the error message i could guess you just made a mistake somewhere inside RootViewController.h, such as a forgotten ; or something like that
you must have imported the this class in the class to which you want to import here. That is why you are getting error , but it can be rectify by #class example .
#class is a forward declaration, a good practice is to put them in the .h instead of #import for avoiding circular #import problem.