Khalizar
Khalizar

Reputation: 307

understanding the correct usage of pointers

i'm declaring two property inside my interface both of them should be pointers, but xcode gives me two different errors..

// myClass.h

#import <Foundation/Foundation.h>

@class CCNode;

@interface myClass : NSObject
{
    NSMutableArray myArray;
    CCNode myNode;
}

for the NSMutableArray:

Interface type cannot be statically allocated

for the CCNode:

Field has incomplete type 'CCNode'

in both cases, using pointers will solve the issue, but what's the difference between them?

with try-and-error approach, i found out that if i change @class CCNode to #import "CCNode.h" then it gives me the same error as the first line, but i'm definetly missing something for the correct understanding....

Upvotes: 1

Views: 280

Answers (4)

Pandey_Laxman
Pandey_Laxman

Reputation: 3908

In Objective-C, you can't allocate an object on the stack, so the point is kind of moot. Objective-C requires that all objects are dynamically allocated (i.e. on the heap). The error you're getting indicates that you're trying to create a CCNode object on the stack. All Objective Class objects are pointer types.

Statically allocated variables are used for primitive C types like int or double

int marks=100;

Upvotes: 0

wbyoung
wbyoung

Reputation: 22493

@class is a forward declaration of your class. It has incomplete type because the compiler doesn't know how large it is, whether it's a struct, an object, a builtin type, etc. When you import the header, the compiler has all the info it needs.

Upvotes: 2

JeremyP
JeremyP

Reputation: 86651

what's the difference between them?

The compiler knows the full definition of NSMutableArray because its header file is included via the Foundation.h header. All it knows about CCNode is that it is an Objective-C class (thanks to the @class), not how big it is or anything else.

This is why including CCNode.h has the effect of changing the error, because the compiler now knows how big it is.

Upvotes: 4

jlehr
jlehr

Reputation: 15597

Pointers need to be declared with a *, so your declarations should look like this:

@class CCNode;

@interface myClass : NSObject
{
    NSMutableArray *myArray;
    CCNode *myNode;
}

Upvotes: 3

Related Questions