嘿,我是Objective-C 2.0和Xcode的新手,所以请原谅我,如果我在这里缺少一些基本的东西。无论如何,我正在尝试创建一个名为GameView的自己的UIViewController类来显示一个新视图。为了完成游戏,我需要跟踪我想从plist文件加载的NSArray。我已经创建了一个方法'loadGame',我想将正确的NSArray加载到实例变量中。但是,似乎在方法执行后,实例变量丢失了数组的跟踪。如果我只是向你展示代码,它会更容易....
@interface GameView : UIViewController {
IBOutlet UIView *view
IBOutlet UILabel *label;
NSArray *currentGame;
}
-(IBOutlet)next;
-(void)loadDefault;
...
@implementation GameView
- (IBOutlet)next{
int numElements = [currentGame count];
int r = rand() % numElements;
NSString *myString = [currentGame objectAtIndex:(NSUInteger)r];
[label setText: myString];
}
- (void)loadDefault {
NSDictionary *games;
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"Games.plist"];
games = [NSDictionary dictionaryWithContentsOfFile:finalPath];
currentGame = [games objectForKey:@"Default"];
}
当调用loadDefault时,一切都运行得很好,但是当我尝试稍后在方法调用next中使用currentGame NSArray时,currentGame似乎是nil。我也知道这段代码的内存管理问题。任何帮助都会受到这个问题的欢迎。
答案 0 :(得分:2)
如果该代码有效,我会感到惊讶。 Games.plist
是否真的位于捆绑的顶层?它不在您的软件包资源文件夹或文档或应用程序支持中?我打赌如果你调试方法,你会发现你没有正确找到它。
答案 1 :(得分:0)
-objectForKey:
不会返回您拥有的对象,您需要通过保留:
currentGame = [[games objectForKey:@"Default"] retain];
或者使用声明的属性:
@interface GameView ()
@property (readwrite, retain) NSArray *currentGame;
@end
@implementation GameView
@synthesize currentGame;
// ...
- (void)loadDefault {
// ...
self.currentGame = [games objectForKey:@"Default"];