2012-05-05 48 views
1

我正在寫一個簡單的遊戲,並認爲它會更容易使用結構。但是,我不能聲明需要結構的方法。使用struct Objective-C方法

我怎樣才能使用一個結構作爲參數到一個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; 
+0

如果您打算使用C數據結構,我建議您熟悉一下如何管理C語言中的內存以及指針如何工作。這個話題太大而無法涵蓋在SO問答中。你的其他選擇是堅持使用Objective-C,這可能不會讓你感到困惑。 – pmdj

回答

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; 

類型的方法需要在括號,你必須參考struct Entity而不是Entity,除非你使用typedef(在Objective-C中,Objective-C++可能讓你這樣做)

2

結構在Objective-C中一直用作參數。例如,的CGRect從蘋果公司的CGGeometry Reference

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

你只需要爲你的結構,它可以以同樣的方式爲蘋果做創建類型,或者本來可以做的

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

所以你的情況:

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

應該允許您定義