确定。我有一个“游戏”类,它创建了我的班级“Board”的实例,并测试它。
“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)
提前,谢谢你的帮助!
答案 0 :(得分: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所在的位置以及那个缺少自我的东西。
答案 1 :(得分: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吗?
另一件事,而不是有两个方法testAgain
和test
。只需拨打test
两次:
for (int i = 0; i <= 2; i++) {
[self test];
}
只是更好的结构,就是这样。请反馈您的结果!