質問

I have two custom classes: FSGame and FSEvent. FSGame has an ivar that should be an NSMutableArray of FSEvent objects.

Here's FSGame.h:

@interface FSGame : NSObject

@property (strong, nonatomic) NSMutableArray *players;
@property (strong, nonatomic) NSString *startTime;
@property (strong, nonatomic) NSString *endTime;
@property (strong, nonatomic) NSMutableArray *gameEvents;

@end

And here's my FSEvent.h:

@interface FSEvent : NSObject

@property NSInteger ID;
@property NSInteger pointTo;

@end

I use

@property (strong, nonatomic) FSGame *game;

to keep an instance of FSGame in my AppDelegate. Then, in my application:didFinishLaunchingWithOptions: I create an instance of FSGame so it can be filled throughout the "game".

_game = [[FSGame alloc] init];

Then, in one of my view controllers, I alloc and init an instance of FSEvent and then attempt to add it to the .gameEvents array:

[appDelegate.game.gameEvents addObject: event];

But something seems to go wrong here because if, from another view controller, I try to get access to that object, it will be nil:

FSEvent *previousEvent = [appDelegate.game.gameEvents lastObject];

if (previousEvent == nil) {
    NSLog(@"previousEvent is NIL!");
}

What am I missing here?

役に立ちましたか?

解決 2

You need to instantiate the arrays, this does NOT happen when you use

_game = [[FSGame alloc] init];

Try using a lazy instantiation in your FSGame class, add this code

-(NSMutableArray *)gameEvents{
    if(!_gameEvents){
        _gameEvents = [NSMutableArray array];
    }
    return _gameEvents;
}

And that should be enough, also make sure of accesing by self.gameEvents and not by _gameEvents!

他のヒント

It's hard to say with the code that's been shown, but it's possible that you never create the mutable array gameEvents and it's nil when you try to access it or add events to it. Make sure you're creating it somewhere, probably in FSGame's -init:

_gameEvents = [NSMutableArray array];

_game.gameEvents is a pointer to a mutable array. It is not initialized, so its value is nil. There are no any mutable array to add objects to.

You can create it when needed writing this method in FSGame.m:

-(NSMutableArray*) gameEvents {
    if ( ! _gameEvents ) {
        _gameEvents = [NSMutableArray array];
    }
    return _gameEvents ;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top