0

嘿,我是 Objective-C 2.0 和 Xcode 的新手,所以如果我在这里遗漏了一些基本的东西,请原谅我。无论如何,我正在尝试制作自己的 UIViewController 类,称为 GameView 来显示新视图。要运行游戏,我需要跟踪要从 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 似乎为零。我也知道这段代码的内存管理问题。对此问题的任何帮助将不胜感激。

4

2 回答 2

2

如果该代码有效,我会感到惊讶。真的Games.plist在你的捆绑包的顶层吗?它不在您的捆绑包的资源文件夹或文档或应用程序支持中?我敢打赌,如果您调试该方法,您会发现您没有正确定位它。

于 2010-06-10T18:35:37.630 回答
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"];
于 2010-06-10T18:32:03.810 回答