Re: NSTimer
Re: NSTimer
- Subject: Re: NSTimer
- From: James Bucanek <email@hidden>
- Date: Tue, 3 Apr 2007 12:57:18 -0700
Bill Allaire wrote on Tuesday, April 3, 2007:
>I'm new to Cocoa, so please bear with me.
We've all been there.
>I initialize a timer when overriding init:
> timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self
>selector:@selector(setDevState:) userInfo:nil repeats:YES];
>
>I create an array to manipulate during each timer event in awakeFromNib:
> tableArray = [NSArray arrayWithObjects:aisle1Table, aisle2Table,
>aisle3Table, nil];
>Each object is a NSTableView.
>
>-(void)setDevState:(NSTimer *)aTimer
>{
> Some calls to Mysql
> ...
> if ([dsdsst compare:@"ONLINE"] == NSOrderedSame)
> [[tableArray objectAtIndex: aisle] setBackgroundColor:green]; //
>Green is NSColor *
> else
> [[tableArray objectAtIndex: aisle] setBackgroundColor:red]; // Same
>with red
> ...
>}
>
>In awakeFromNib: I call:
> [self setDevState:timer];
>
>When the program runs, the three tables are colored according to
>their status (online or offline) as expected. In the debugger the
>tableArray has a count of three objects. When the timer fires and
>enters setDevState: the count of tableArray shows and when this
>object is accessed, GDB is brought up:
> {(int)[$VAR count]} objects
That's because tableArray is now invalid.
When you created tableArray is was autoreleased. It is, essentially, a temporary object. It will exist for the duration of the current autorelease pool, which is destroyed at the end of every run loop event dispatch. All of your calls in init occur within the same run loop event, so tableArray is still valid.
>If I comment out the line [self setDevState:timer]; and wait for the
>timer to fire, the debugger is brought up with the same behavior: no
>count in the array. I don't understand why I can call setDevState:
>outside a timer and it works fine but when called by way of the timer
>things go awry.
By the time the timer fires, tableArray has long since been destroyed.
You need to add [tableArray retain] to your init and release it again in your dealloc method.
You should probably review the Cocoa memory management basics. <file:///Developer/ADC Reference Library/documentation/Cocoa/Conceptual/MemoryMgmt/index.html#//apple_ref/doc/uid/10000011i>
Also look up the various NSZombie settings. NSZombie is the easiest way to discover overreleased objects. <http://developer.apple.com/technotes/tn2004/tn2124.html>
--
James Bucanek
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden
References: | |
| >NSTimer (From: Bill Allaire <email@hidden>) |