1

私は単純なゲームを書いていますが、構造を使用する方がはるかに簡単だと思いました。ただし、構造体を必要とするメソッドを宣言することはできません。

Objective-C メソッドの引数として構造体を使用し、返された構造体のオブジェクトを取得するにはどうすればよいですか?

//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;
4

2 に答える 2

3

構造体は期待どおりに使用できますが、問題はメソッドの構文にあるようです。

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;

メソッドの型は括弧で囲む必要があり、typedef を使用しない限り、struct Entity代わりに参照する必要があります (プレーンな Objective-C では、Objective-C++ で実行できる場合があります)。Entity

于 2012-05-05T16:04:49.723 に答える
2

構造体は、Objective-C のパラメーターとして常に使用されます。たとえば、Apple のCGGeometry Referenceの CGRect

struct CGRect {
  CGPoint origin;
  CGSize size; 
}; 
typedef struct CGRect CGRect;

構造体の型を作成するだけで済みます。これは、Apple と同じ方法で行うことができます。

typedef struct CGRect {
  CGPoint origin;
  CGSize size; 
} CGRect;

だからあなたの場合:

typedef struct
{
  int entityX;
  int entityY;
  int entityLength;
  int entityWidth;
  int entityType;
  bool isDead;
} Entity;

定義できるようにする必要があります

-(BOOL)detectCollisionBetweenEntity:(Entity) ent1 andEntity:(Entity) ent2;
-(Entity)createEntityWithX:int newEntityX andY:int newEntityY, withType:int newEntityType withWidth:int newEntityWidth andLength:int newEntityLength;
于 2012-05-05T16:07:54.430 に答える