views:

49

answers:

2

This is my first time working with Objective-C, and I keep trying to create objects of classes I have created in methods of other classes, and it will not work. What I mean is for instance, I will have one main class, and one of the methods does something like this:

exampleclass *instance1 = [[exampleclass alloc] init]

And it says that exampleclass is undeclared. exampleclass is in another file, and my main class can't contact it, or at least that is what I think is happening. Why can't it find exampleclass and create an instance of it?

+4  A: 

Have you imported the header for this class in the source file where you are trying to use it? Add something like:

#import "exampleclass.h"

at the file top with the other header imports. That's assuming that you named your files after your classes.

No one in particular
Thank you so much! I was pulling my hair out over this.
Regan
+1  A: 

When compiling C or Objective-C source files, each .c and .m file is interpreted independently with no knowledge of other source files. Headers are used to describe what can be found in other source files (they declare that things exist but they do not include the definition), so if one of your source files wants to use something from another source file, you need to make sure that the compiler is aware of it, and this is done by including the header that describes/declares it.

If you have a header file called exampleclass.h, and this header contains the declaration of exampleclass, then you need to import this header to tell the compiler that the class exists, otherwise it will complain that it is undeclared.

#import "exampleclass.h"
// now compiler is aware of exampleclass.
...
...
dreamlax