开发者

In Objective-C, objects can't be method parameters. How can I create mutually pointing objects then?

[New to Objective-C, struggling with things that are straightforward in other languages.]

I would like to do something like this:

@interface GameBoard : NSObject {
    // ..
GameState *parentGameState;
}

- (GameBoard) initStartGame (GameState *) parent;

so that a GameState (which has a GameBoard pointer as a member)开发者_Python百科 could create a GameBoard that in turn has a pointer back to the GameState that created it.

However, it seems that in Objective-C neither objects nor pointers to objects can be method parameters.

So what's the idiom for creating a pair of objects each of which points to the other? There must be a way, otherwise you couldn't do basic things like e.g. doubly linked lists.


Pointers to objects can be method parameters, you just have the wrong syntax

 - (id) initStartGame: (GameState *) parent; // you forgot the colon

init methods usually return id -- but if you wanted to return a specific type, use GameBoard*, which would not be idiomatic.

You might need to make a forward declaration with @class (to avoid mutual imports).

So instead of

#import "GameState.h"

use

@class GameState;

in GameBoard.h

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜