Objective-C int variable not keeping its value
here is an absolute brain destroyer:
NOTE: I am using XCode 4.2 with iOS 5 and ARC (Automatic Reference Counting)
If anybody can help explain why none of my variables are retaining their value I will be grateful beyond reason. Currently I have this int variable speed. Heres the basic code rundown:
In Header File:
@interface GameLoop : NSObject {
CADisplayLink *refresh;
int speed;
}
In .m File:
- (void)awakeFromNib {
screenRefresh = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateGame:)];
[screenRefresh setFrameInterval:1];
[screenRefresh addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}
- (void)createNewGame {
speed = 4;
}
- (void)updateGame:(CADisplayLink *)gameTime {
[factory slideViews:speed]; // <---- Speed ALWAYS equals 0
}
The factory class simply moves stuff around. If I plug in 4 in place of speed everything works perfectly. I have also tried making speed by:
@property (nonatomic, assign) int speed;
And synthesising and using self.speed
. If anyone can help, I would be very thankful! I'm sure it's something simple, but just the fact that I assign in one method and it doesn't follow through in another drives me insane. I also have used NSLog("%d", speed)
and it spits out the correct value in the method I assign it in, and w开发者_运维百科hen I re-call it before assigning.
Update After a little debugging, it appears as though once the timer is created, no global variables are updated within the update loop. If I make speed = 4 before allocating the CADisplayLink, the game runs at 4. However even if I make proper changes to speed it does not change. Anybody know why?
Are you sure that speed ivar is not keeping the value? Could you try the following code?
- (void)createNewGame {
NSLog(@"createNewGame: speed <- 4");
speed = 4;
NSLog(@"createNewGame: speed = %d", speed);
}
- (void)updateGame:(CADisplayLink *)gameTime {
NSLog(@"updateGame before slideViews: speed = %d", speed);
[factory slideViews:speed]; // <---- Speed ALWAYS equals 0
NSLog(@"updateGame after slideViews: speed = %d", speed);
}
Do you have any code to overwrite for speed ivar?
Okay, so the problem had to do with something larger than the context of which I originally thought it was on. The problem was that I wasn't properly allocating things into memory, and because of that I was assigning to nil variables.
精彩评论