2

行。我有一个“游戏”类,它创建了我的“棋盘”类的一个实例,并对其进行了测试。

“Board”类有一个字典,它似乎无法保持它的值(?)试图将代码限制到最小:

游戏类:

@interface Game : UIViewController{
    Board *board;
}
-(void)testAgain; 

@implementation Game
-(void)setup{
    board = [Board alloc]createBoard];
    [board test]; //returns right value
    [self testAgain]; //returns (null), see output below
}
-(void)testAgain{
    [board test];
}

-(void)didLoad{
    [self setup];
}

板级:

@interface Board : NSObject{
@property(nonatomic, retain) NSMutableDictionary *dict;

-(Board *)createBoard;
-(void)test;

@implementation Board
@synthesize dict;

-(Board *)createBoard{

    dict = [[NSMutableDictionary alloc]init];

    [dict setObject:@"foo1" forKey:@"1"];
    [dict setObject:@"foo2" forKey:@"2"];
    [dict setObject:@"foo3" forKey:@"3"];
    [dict setObject:@"foo4" forKey:@"4"];
    [dict setObject:@"foo5" forKey:@"5"];

    return self;
}

-(void)test{
    NSLog(@"Test return: %@", [dict objectForKey:@"4"]);
}

以下输出:

2012-06-23 01:05:28.614 Game[21430:207] Test return: foo4
2012-06-23 01:05:32.539 Game[21430:207] Test return: (null)

在此先感谢您的帮助!

4

2 回答 2

1
@implementation Game
-(void)setup{
    board = [[[Board alloc] init] createBoard];
    [board test]; //returns right value
    [self testAgain]; //returns (null), see output below
}

您使用的创建模式超出了 Objective-C 的所有约定。您应该使用 [Board new]、[[Board alloc] init|With...|] 或 [Board board|With...|]。

-(Board *)createBoard {

    self.dict = [[NSMutableDictionary alloc]init];

    [dict setObject:@"foo1" forKey:@"1"];
    [dict setObject:@"foo2" forKey:@"2"];
    [dict setObject:@"foo3" forKey:@"3"];
    [dict setObject:@"foo4" forKey:@"4"];
    [dict setObject:@"foo5" forKey:@"5"];
}

让我们看看您的代码是否在丢失的 init 重新安装到它所属的位置以及那个小小的丢失的 self 的情况下工作得更好。.

于 2012-06-23T00:14:15.917 回答
0

首先,您没有正确地Board使用createBoard. 您甚至没有Board在该方法中返回对象。尝试将该方法修改为如下所示:

-(id)initWithCreatedBoard {

self = [super init];


if (self) { 

dict = [[NSMutableDictionary alloc]init];

[dict setObject:@"foo1" forKey:@"1"];
[dict setObject:@"foo2" forKey:@"2"];
[dict setObject:@"foo3" forKey:@"3"];
[dict setObject:@"foo4" forKey:@"4"];
[dict setObject:@"foo5" forKey:@"5"];

[dict retain];

}

回归自我;

}

你也可能想要retain dict. 因为他们可能正在被释放。

另外,您使用ARC吗?

另一件事,而不是有两个方法testAgaintest. 只需调用test两次:

for (int i = 0; i <= 2; i++) {

[self test];

}

只是更好的结构,就是这样。请反馈您的结果!

于 2012-06-23T00:12:05.123 回答