1

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;
1
  • If you're going to use C data structures I suggest you familiarise yourself with how you manage memory in C, and how pointers work. This topic is far too big to cover in a SO question & answer. Your other option is to stick with Objective-C, this might be less confusing to start off with. Commented May 5, 2012 at 15:59

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

Comments

2

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.