iosobjective-cuiviewsetneedsdisplay

Can't pass int to UIView with drawRect


How do I pass an int to a UIView that is using drawRect to make me a circle arc?

I'm trying to draw a circle arc, and every second, call setNeedsDisplay on the UIView with an int advanced by one (secs). This doesn't seem to be calling and remains (null) when I call NSLog(@"draw, %d",self.secs);

basically my code log just reads "draw 1" followed by "draw 0" every second.

draw.h

@property (nonatomic) int secs;

draw.m

@synthesize secs;

- (void)drawRect:(CGRect)rect
{
    NSLog(@"draw, %d",self.secs);
    //stuff with using this value   
}
@end

main VC.m - NSTimer calls this, but tick.secs seems to be 0 every time

draw *tick = [[draw alloc] init];
tick.secs = tick.secs+1;
NSLog(@"draw, %d",tick.secs);
[self.drawView setNeedsDisplay];

EDIT 1:

Stonz2 is quite correct, I should use an instance draw - this has solved half of my problem. Now in my main VC.m, tick.secs is increasing every second, but in draw.m, drawRect still thinks secs is 0 every second

EDIT 2: Sha fixed it with his observation of my IBOutlet using UIView, not draw


Solution

  • The problem is that you're creating a new draw object every time you run through your timed method. You need to keep the same reference to your draw object if you want to maintain its properties.

    Consider creating an instance draw object in your main VC.m file instead of creating a new one every time you run your timed method.

    Example:

    @implementation mainVC
    {
        draw *tick;
    }
    
    ...
    
    - (void)startTimer
    {
        tick = [[draw alloc] init];
        tick.secs = 0;
        // start your timer here
    }
    
    - (void)timerIncrement
    {
        // do NOT alloc/init your draw object again here.
        tick.secs += 1;
        [self.drawView setNeedsDisplay];
    }