开发者

Why doesn't my UIViewController class keep track of an NSArray instance variable

开发者 https://www.devze.com 2023-01-03 13:57 出处:网络
Hey, I am new to Objective-C 2.0 and Xcode, so forgive me if I am missing something elementary here. Anyways, I am trying to make my own UIViewController class called GameView to display a new view. T

Hey, I am new to Objective-C 2.0 and Xcode, so forgive me if I am missing something elementary here. Anyways, I am trying to make my own UIViewController class called GameView to display a new view. To work the game I need to keep track of an NSArray that I want to load from a plist file. I have made a method 'loadGame' which I want to load the correct NSArray into an instance variable. However it appears that after the method executes the instance variable loses track of the array. Its easier if I just show you the code....

    @interface GameView : UIViewController {
        IBOutlet UIView *view 
        IBOutlet UILabel *label;
        NSArray *currentGame;
    }

    -(IBOutlet)next;
    -(void)loadDefault;
...
@implementation GameView
开发者_StackOverflow社区- (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"];
}

when loadDefault gets called, everything runs perfectly, but when I try to use the currentGame NSArray later in the method call to next, currentGame appears to be nil. I am also aware of the memory management issues with this code. Any help would be appreciated with this problem.


I would be surprised if that code worked. Is Games.plist really at the top level of your bundle? It's not in your bundle's resources folder or in Documents or Application Support? I bet if you debug the method, you'll see that you're not correctly locating it.


-objectForKey: doesn't return an object you own, you need to take ownership explicitly by retaining:

currentGame = [[games objectForKey:@"Default"] retain];

Or by using declared properties:

@interface GameView ()
@property (readwrite, retain) NSArray *currentGame;
@end

@implementation GameView
@synthesize currentGame;
// ...
- (void)loadDefault {
    // ...
    self.currentGame = [games objectForKey:@"Default"];
0

精彩评论

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