Reputation: 422
I'm writing a simple game, and thought it would be much easier to use structures. However, I can't declare methods that need the structs.
How could I use a struct as an argument to an Objective-C method and get an object of the struct returned?
//my structure in the .h file
struct Entity
{
int entityX;
int entityY;
int entityLength;
int entityWidth;
int entityType;
bool isDead;
};
//And the methods i'm trying to use
-(BOOL)detectCollisionBetweenEntity:Entity ent1 andEntity:Entity ent2;
-(struct Entity)createEntityWithX:int newEntityX andY:int newEntityY, withType:int newEntityType withWidth:int newEntityWidth andLength:int newEntityLength;
Upvotes: 1
Views: 2526
Reputation: 7513
Structs are used as parameters in Objective-C all the time. For example the CGRect from Apple's CGGeometry Reference
struct CGRect {
CGPoint origin;
CGSize size;
};
typedef struct CGRect CGRect;
You just have to create a type for your struct, which can be done in the same way as Apple, or could have been done as
typedef struct CGRect {
CGPoint origin;
CGSize size;
} CGRect;
So in your case:
typedef struct
{
int entityX;
int entityY;
int entityLength;
int entityWidth;
int entityType;
bool isDead;
} Entity;
Should allow you to define
-(BOOL)detectCollisionBetweenEntity:(Entity) ent1 andEntity:(Entity) ent2;
-(Entity)createEntityWithX:int newEntityX andY:int newEntityY, withType:int newEntityType withWidth:int newEntityWidth andLength:int newEntityLength;
Upvotes: 2
Reputation: 70775
You can use structs exactly like you would expect, your problem seems to be with the syntax of methods:
struct Entity
{
int entityX;
int entityY;
int entityLength;
int entityWidth;
int entityType;
bool isDead;
};
//And the methods i'm trying to use
-(BOOL)detectCollisionBetweenEntity:(struct Entity) ent1 andEntity:(struct Entity) ent2;
-(struct Entity)createEntityWithX:(int) newEntityX andY:(int) newEntityY withType:(int) newEntityType withWidth:(int) newEntityWidth andLength:(int) newEntityLength;
Types in methods need to be in parens, and you have to refer to struct Entity
instead of Entity
unless you typedef (in plain Objective-C, Objective-C++ might let you do it)
Upvotes: 3