Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does @class do in iOS 4 development?

Is there any difference in doing

@class MyViewController;

rather than doing the normal import of the .h into the appdelegate.h

#import "MyViewController.h"

I've seen some example recently that use the @class way and wondered if there any differences.

thanks.

like image 344
user868830 Avatar asked Jul 29 '11 11:07

user868830


People also ask

What is Interface Objective C?

In Objective-C, the class interface specifies exactly how a given type of object is intended to be used by other objects. In other words, it defines the public interface between instances of the class and the outside world.

What is a class in Xcode?

Structures and classes are general-purpose, flexible constructs that become the building blocks of your program's code. You define properties and methods to add functionality to your structures and classes using the same syntax you use to define constants, variables, and functions.

How do I create an instance of a class in Objective C?

You can create a class reference with the following code: Class M = [NSMutableString class]; // NSMutableString (for example). You can then call methods on that saved class with code like this: [M string];


1 Answers

There is a big difference.

@class MyViewController;

Is a forward declaration for the object MyViewController. It is used when you just need to tell the compiler about an object type but have no need to include the header file.

If however you need to create an object of this type and invoke methods on it, you will need to:

#import "MyViewController.h"

But normally this is done in the .m file.

An additional use of forward declarations is when you define a @protocol in the same header file as an object that uses it.

@protocol MyProtocolDelegate; //forward declaration

@interface MyObject {
    id<MyProtocolDelegate> delegate;
    ...
}
...
@end

@protocol MyProtocolDelegate
    ... //protocol definition
@end

In the above example the compiler needs to know that the @protocol MyProtocolDelegate is valid before it can compile the MyObject object.

Simply moving the protocol definition above MyObject definition would also work.

like image 121
Richard Stelling Avatar answered Sep 27 '22 21:09

Richard Stelling