The error of NSTimer - iphone

I add a NSTimer in the iphone application。When I run the application,it‘s failed。I have tracked it and found that it stop at “0x3050c3ad <+0013> call 0x306aeaa5 ” and cann't go on in Debugger。
If you know,please tell me what’s wrong with the application and how to solve it。
Thank you!
The code is:
NSTimer *m_heartBeatTimer;
#property(nonatomic, retain) NSTimer *m_heartBeatTimer;
#synthesize m_heartBeatTimer;
-(void)HeartBeatTimer:(NSTimer *)timer
{
[csocket CloseSocket];
}
case PING:
{
[self SendDataToServer:"00" Type:PONG];
if(m_heartBeatTimer != nil)
[m_heartBeatTimer invalidate];
m_heartBeatTimer = [NSTimer scheduledTimerWithTimeInterval:6.0 target:self selector:#selector(HeartBeatTimer:) userInfo:nil
repeats:NO];
} break;

lqf,
First you should access the timer via self.m_heartBeatTimer since you declared it as retained in the #property declaration. If you don't use the self. prefix, you aren't using the setter and therefore you aren't retaining the timer like you specified in the #property declaration.
I have no clue what your obscure error message is, but I'm guessing it's memory related. Make sure you use that self. prefix and let me know if that works. If you actually had an error message of EXC_BAD_ACCESS output on the Run Console, please update your post with that so it's something people can work with.
-Rob

Related

Stop performing the animation in background thread and run loop

I run my animations in a UITAbleViewCell.
Each cell has its own animation and the cells are reusable.
I use [mView performSelectorInBackground:#selector(layoutSubview) withObject:nil];
There in the background thread I initiate the runLoop to perform tasks like this:
- (void)startAnimation
{
NSRunLoop *mLoop = [NSRunLoop currentRunLoop];
self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval target:self selector:#selector(setNeedsDisplay) userInfo:nil repeats:YES];
mRunLoop = YES;
while (mRunLoop == YES && [mLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.01]]);
}
and stop it:
- (void)stopAnimation
{
if (![NSThread isMainThread]) {
[[NSThread currentThread] cancel];
}
mRunLoop = NO;
self.animationTimer = nil;
CFRunLoopStop(CFRunLoopGetCurrent());
}
I run into problems when I fast scroll through table, because on the first cell initiation I begin the animation, so the first runLoop call occures which performs a setNeedDisplay and all the methods from it. But before finishing the first runLoop cycle the cell disappears from the view and is already available for reuse. So I begin clearing it, while the cycle is still performing operations and here I meet situations like
message sent to deallocated instance
So could you please give me some hints of how should I correctly stop performing the operations in that thread? I mean if I want to realese for example an object, which is performing some actions how to immediately stop'em?
Hope I gave enough info.
Thanks
UPDATE: No ideas at all?
I'll take a completely different stab on it:
Get rid of the cell's timers and background threads altogether!
Animation is not something where NSTimer is a good fit in the first place and having multiple timers won't help much, either.
UITableView has a method visibleCells and a method indexPathsForVisibleRows. I'd suggest to use a single CADisplayLink — which is suited for animation, as it calls you back with the actual refresh rate of the display or a fraction thereof — in your tableview-controller and in the callback of that display-link iterate over the visible cells.
If you want to schedule the display-link on the run-loop of a secondary thread, feel free to do so, but I'd check if you can get away without extra threading first.
Some code:
#interface AnimatedTableViewController ()
#property (strong, nonatomic) CADisplayLink *cellAnimator;
- (void)__cellAnimatorFired:(CADisplayLink *)animator;
#end
#implementation AnimatedTableViewController
#synthesize cellAnimator = cellAnimator_;
- (void)setCellAnimator:(CADisplayLink *)animator
{
if (animator == cellAnimator_)
return;
[cellAnimator_ invalidate];
cellAnimator_ = animator;
[cellAnimator_ addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSCommonRunLoopModes];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
self.cellAnimator = [CADisplayLink displayLinkWithTarget:self selector:#selector(__cellAnimatorFired:)];
...
}
- (void)viewWillDisappear:(BOOL)animated
{
self.cellAnimator = nil;
...
[super viewWillDisappear:animated];
}
- (void)__cellAnimatorFired:(CADisplayLink *)animator
{
NSArray *visibleCells = [self.tableView visibleCells];
[visibleCells enumerateObjectsUsingBlock:^(UITableViewCell *cell, NSUInteger unused, BOOL *stop){
[cell setNeedsDisplay];
}];
}
...
#end
NSTimer has a -cancel method that stops the timer from firing. Calling it in -prepareForReuse (and, for that matter, in -stopAnimation) may help.
However, this code looks rather dangerous. Nesting run loops like this is almost never a good idea—and moreover, as far as I can tell it's totally unnecessary. If you let -startAnimation return, your animation timer will still get run on the main run loop. And if you're doing it this way because there's some code after -startAnimation that you want to delay, you should restructure your code so this isn't needed.
(If you drop the runloop stuff in -startAnimation, don't stop the runloop in -stopAnimation either.)
Something like the approach danyowdee recommends would be even better, but at least get rid of this runloop stuff. It's just asking for trouble.
I think you can use this method for your problem
[NSObject cancelPreviousPerformRequestsWithTarget:yourTarget selector:aSelector object: anArgument];
I think that the best way to avoid that behavior is assigning the delegate that receives the cancel method in other class that won't be reused. For example, you can have a private array of instances that process all the cancel methods, each row mapped into an array element.
I recommend you the lazy tables example provided by Apple in Xcode documentation. It's a great example of how to load images asynchroniously in background with a table. I think that also it would be useful for you for the scrolling subjects (decelerating and paging).
Only one more consideration, i don't recommend messing up with several cfrunloopstop, test it hard!

NSTimer invalidate not working

I am trying to create an explosion on the iphone screen which gets bigger fast, then goes away. Why is this timer not stopping?
NSTimer *explosion = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(explosion) userInfo:nil repeats:YES];
-(void)explosion {
image.image = [UIImage imageNamed:#"explosion.png"];
expsize = expsize + 2.5;
image.frame = CGRectMake(image.frame.origin.x, image.frame.origin.y, expsize, expsize);
if (expsize > 60) {
NSLog(#"%f",expsize);
[explosion invalidate];
explosion = nil;
}
}
You are most likely invalidating the wrong timer.
You create a local variable named explosion that has the same name as the instance variable.
Avoid declaring instance variables and local variables with the same name!
I'd suggest that you use the form of selector that the NSTimer doc calls for: - (void)timerFireMethod:(NSTimer*)theTimer. The you can invalidate "theTimer" and be sure you're invalidating the right one.
Also, of course, if "explosion" is declared as a property, then there will be two methods in the class named "explosion", and no real clue as to which one is getting called.
It's hard to be certain, because it's not clear whether this is exactly your code, but you have two variables named explosion, and one of them has an NSTimer assigned to it; the other (which seems to be an ivar) is nil.
// Variable local to whatever method this is in
NSTimer *explosion = [NSTimer scheduledTimerWithTimeInterval:0.1...
if (expsize > 60) {
NSLog(#"%f",expsize);
// Other variable named "explosion" does not exist.
// This is an ivar? Has not been set.
[explosion invalidate];
Assuming you've got explosion declared as a property (and there is no reason not to), you should fix this by using the setter when you create the timer:
[self setExplosion:[NSTimer scheduledTimerWithTimeInterval:...]];
Now the ivar has the timer instance and you can use it to invalidate the timer.
Also, note that your timer's method is incorrect; it must take one parameter which is a pointer to the timer. You can also use this pointer to invalidate the timer when it fires.
- (void) fireExplosion: (NSTimer *)tim {
//...
if( expsize > 60 ){
[tim invalidate];
//...
}
}
Finally, you have one last naming problem; if your property is called explosion, the convention in Cocoa is that the accessor should have the same name, but you have used explosion for the method that your timer calls. This could cause hard-to-track problems later. You should rename the timer method as I have here, using a verb indicating that something is happening.
If you are declaring explosion how you posted in your example then you are shadowing your instance variable explosion. As a word of advice you should use a naming convention for instance variables such as an underscore prefix. Now keeping track of the timer is not required if you only invalidate it after it fires. You could just take an extra parameter on the explosion method that would be the timer explosion:(id)timer. Otherwise you can do the following.
#interface X : NSObject
{
NSTimer *_explosion;
}
#end
And when you go to declare it in your code do the following
...
[_explosion invalidate];
[_explosion release];
//There is a whole 'nother debate on whether or not to retain a scheduled timer
//but I am a stickler for ownership so remember to release this in dealloc
_explosion = [[NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:#selector(explosion)
userInfo:nil
repeats:YES] retain];
...
-(void)explosion {
image.image = [UIImage imageNamed:#"explosion.png"];
expsize = expsize + 2.5;
image.frame = CGRectMake(image.frame.origin.x, image.frame.origin.y, expsize, expsize);
if (expsize > 60) {
NSLog(#"%f",expsize);
[_explosion invalidate];
[_explosion release];
_explosion = nil;
}
}

NSTimer is not getting stopped

I am trying to stop the timer. My problem is when I try to stop the timer the value of timer is nil and it is not getting invalidated. if there any way to stop the timer except this ?
My code is like
timer is defined in header file - and also synthesized.
if([str_Message isEqualToString:ON] // if the command to start timer
{
if(!timer)
{
tmr_CallWebService = [[NSTimer scheduledTimerWithTimeInterval:Time_TracingInterval target:ClassTracing selector:#selector(startLocationTracing) userInfo:nil repeats:YES]retain];
}
//to stop timer
else if([str_Message isEqualToString:OFF])
{
if(timer)
{
[timer invalidate];
timer = nil;
}
Please help me out... thanks in advance
I think you just need to replace tmr_CallWebService with timer.
[str_Message isEqualToString:ON] should be like this [str_Message isEqualToString:#"ON"]. similarly for the comparison with OFF. Use #"OFF".
If you've got a property declared for the timer, you should use it. For instance, if your timer is defined as #property (nonatomic, retain) NSTimer *myTimer; you should refer to it as self.myTimer and set it using that setter and invalidate it later using the accessor.
It looks like you're not setting tmr_CallWebService to your timer ivar at any place so you're just leaking and losing the reference.

Repeating NSTimer, weak reference, owning reference or iVar?

I thought I would put this out here as a separate question from my previous
retaining-repeating-nstimer-for-later-access as the discussion has moved forward making a new question clearer than yet another EDIT:
The scenario is an object creates a repeating NSTimer, lets say in viewDidLoad, once created the NSTimer needs to stay around so it can be accessed by other methods.
NSTimer *ti = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(updateDisplay:)
userInfo:nil
repeats:YES];
I understand that when created the runloop takes ownership of the NSTimer and ultimately stops, removes and releases the NSTimer when [ti invalidate]; is called.
By virtue of the fact that we need to access the NSTimer in more than one method we need some way to hold a reference for future use, the revised question is:
// (1) Should the NSTimer be held using an owning reference (i.e.)
#property(nonatomic, retain) NSTimer *walkTimer;
[self setWalkTimer: ti];
...
...
// Cancel method
[[self walkTimer] invalidate;
[self setWalkTimer:nil];
...
...
// dealloc method
[walkTimer release];
[super dealloc];
.
// (2) Should the NSTimer be held using a weak reference (i.e.)
#property(nonatomic, assign) NSTimer *walkTimer;
[self setWalkTimer: ti];
...
...
// Cancel method
[[self walkTimer] invalidate];
[self setWalkTimer:nil];
...
...
// dealloc method
[super dealloc];
.
// (3) Use an iVar and rely on the runLoop holding (i.e. retaining) the timer
NSTimer *walkTimer;
NSTimer *walkTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(updateDisplay:)
userInfo:nil
repeats:YES];
...
...
// Cancel method
[walkTimer invalidate];
walkTimer = nil;
.
// (4) Something not listed above ...
I am happy for just (1) (2) (3) or (4) as a lot of discussion regarding which is best has already been written on the Other thread. There does seem to be a lot of conflicting answers so I hope this more specific question will help focus on what might be best practice in this situation.
EDIT:
As a side note in the Apple NSTimer Class Reference 4 out of 5 of the sample code projects use NSTimers that are assigned** to a retained property. Here is an example of what the class reference examples show:
#property (nonatomic, retain) NSTimer *updateTimer;
updateTimer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:#selector(updateCurrentTime) userInfo:p repeats:YES];
...
...
// Cancel
[updateTimer invalidate];
updateTimer = nil;
...
...
// Dealloc method
[super dealloc];
[updateTimer release];
** It should be noted that in the examples Apple are assigning the iVar directly and not using the property setter.
After giving it all some more thought and finding an important flaw in my reasoning, I've come to a different conclusion:
It doesn't matter much, whether you hold an owning or a non-owning reference to a timer that you need to invalidate. It is completely a matter of taste.
The deal breaker is, what the target of the timer is:
If the object that creates a timer is its target, managing that object's lifetime becomes more fragile: it cannot simply be retain/release managed, instead you need to ensure that the client that holds the last reference to this object makes it invalidate the timer before it disposes of it.
Let me illustrate the situation with a couple of sort-of-object-graphs:
You start in a state from which you setup the timer and set yourself as the target. Setup of the Timer: yourObject is owned by someClientObject. In parallel exists the current run-loop with an array of scheduledTimers. the setupTimer method is called upon yourObject:
The result is the following initial state. In addition to the former state yourObject now has a reference (owned or not) to the workTimer, which in turn owns yourObject. Furthermore, workTimer is owned by the run-loops scheduledTimers array:
So now you'll use the object, but when you're done with it and simply release it, you'll end up with simple release leak: after someClientObject disposes of yourObject through a simple release, yourObject is disassociated from the object-graph but kept alive by workTimer. workTimer and yourObject are leaked!
Where you leak the object (and the timer) because the runloop keeps the timer alive, which — in turn — keeps an owning reference to your object.
This can be avoided if yourObject is only ever owned by one single instance at a time, when it is properly disposed of proper disposal through cancellation: before disposing of yourObject through release, someClientObject calls the cancelTimer method on yourObject. Within that method, yourObject invalidates workTimer and (if it owned workTimer) disposes of workTimer through release:
But now, how do you resolve the following situation?
Multiple Owners: Setup like in the initial state, but now with multiple independent clientObjects that hold references to yourObject
There is no easy answer, I am aware of! (Not that the latter has to say much, but...)
So my advice is...
Don't make your timer a property/don't provide accessors for it! Instead, keep it private (with the modern runtime I think you could go so far as to define the ivar in a class extension) and only deal with it from one single object. (You may retain it, if you feel more comfortable doing so, but there is absolutely no need for it.)
Caveat: If you absolutely need to access the timer from another object, make the property retain the timer (as that is the only way to avoid crashes caused by clients that directly invalidated the timer they accessed) and provide your own setter. Rescheduling a timer is — in my opinion — not a good reason to break encapsulation here: provide a mutator if you need to do that.
Set the timer up with a target other than self. (There are plenty of ways doing so. Maybe through writing a generic TimerTarget class or — if you can use it — through a MAZeroingWeakReference?)
I apologize for being a moron in the first discussion and want to thank Daniel Dickison and Rob Napier for their patience.
So here is the way I am going to handle timers from now on:
// NSTimer+D12WeakTimerTarget.h:
#import <Foundation/NSTimer.h>
#interface NSTimer (D12WeakTimerTarget)
+(NSTimer *)D12scheduledTimerWithTimeInterval:(NSTimeInterval)ti weakTarget:(id)target selector:(SEL)selector userInfo:(id)userInfo repeats:(BOOL)shouldRepeat logsDeallocation:(BOOL)shouldLogDealloc;
#end
// NSTimer+D12WeakTimerTarget.m:
#import "NSTimer+D12WeakTimerTarget.h"
#interface D12WeakTimerTarget : NSObject {
__weak id weakTarget;
SEL selector;
// for logging purposes:
BOOL logging;
NSString *targetDescription;
}
-(id)initWithTarget:(id)target selector:(SEL)aSelector shouldLog:(BOOL)shouldLogDealloc;
-(void)passthroughFiredTimer:(NSTimer *)aTimer;
-(void)dumbCallbackTimer:(NSTimer *)aTimer;
#end
#implementation D12WeakTimerTarget
-(id)initWithTarget:(id)target selector:(SEL)aSelector shouldLog:(BOOL)shouldLogDealloc
{
self = [super init];
if ( !self )
return nil;
logging = shouldLogDealloc;
if (logging)
targetDescription = [[target description] copy];
weakTarget = target;
selector = aSelector;
return self;
}
-(void)dealloc
{
if (logging)
NSLog(#"-[%# dealloc]! (Target was %#)", self, targetDescription);
[targetDescription release];
[super dealloc];
}
-(void)passthroughFiredTimer:(NSTimer *)aTimer;
{
[weakTarget performSelector:selector withObject:aTimer];
}
-(void)dumbCallbackTimer:(NSTimer *)aTimer;
{
[weakTarget performSelector:selector];
}
#end
#implementation NSTimer (D12WeakTimerTarget)
+(NSTimer *)D12scheduledTimerWithTimeInterval:(NSTimeInterval)ti weakTarget:(id)target selector:(SEL)selector userInfo:(id)userInfo repeats:(BOOL)shouldRepeat logsDeallocation:(BOOL)shouldLogDealloc
{
SEL actualSelector = #selector(dumbCallbackTimer:);
if ( 2 != [[target methodSignatureForSelector:aSelector] numberOfArguments] )
actualSelector = #selector(passthroughFiredTimer:);
D12WeakTimerTarget *indirector = [[D12WeakTimerTarget alloc] initWithTarget:target selector:selector shouldLog:shouldLogDealloc];
NSTimer *theTimer = [NSTimer scheduledTimerWithTimeInterval:ti target:indirector selector:actualSelector userInfo:userInfo repeats:shouldRepeat];
[indirector release];
return theTimer;
}
#end
Original (for full disclosure):
You know my opinion from your other post:
There is little reason for an owning reference of a scheduled timer (and bbum seems to agree).
That said, your options 2, and 3 are essentially the same. (There is additional messaging involved in [self setWalkTimer:nil] over walkTimer = nil but I'm not sure if the compiler won't optimize that away and access the ivar directly, but well...)
I generally manage the invalidate inside of the accessor so that you never get surprised by a timer accessing you after you think you got rid of it:
#property(nonatomic, retain) NSTimer *walkTimer;
[self setWalkTimer: ti];
- (void)setWalkTimer:(NSTimer *)aTimer
{
if (aTimer != walkTimer_)
{
[aTimer retain];
[walkTimer invalidate];
[walkTimer release];
walkTimer = aTimer;
}
}
...
...
// Cancel method
[self setWalkTimer:nil];
...
...
// Make a new timer, automatically invalidating the old one
[self setWalkTimer:[... a new timer ...]]
...
...
// dealloc method
[walkTimer_ invalidate];
[walkTimer_ release];
[super dealloc];

NSTimer not stopping

I have a Class with a NSTimer *myTimer; variable. At some point I do:
myTimer = [NSTimer scheduledTimerWithTimeInterval:20 target:self selector:#selector(doStuff) userInfo:nil repeats: YES];
further, I have a method:
- (void)doStuff
{
if(myTimer)
{
//do stuff
}
}
and I stop my timer when the class is released through:
- (void)dealloc
{
if (myTimer) { //if myTimer==nil it already has been stopped in the same way
[myTimer invalidate];
myTimer = nil;
}
}
Now, the problem is that when I release the class the timer goes on and on and on firing the event anyway. Am I doing something wrong? It seems the dealloc method is never called, otherwise myTimer would be nil and even if the selector is fired it would not go into the if(myTimer)
This will never work, because timers retain their target, which means your dealloc method will never get invoked until after you've invalidated the timer.
For more info, see the NSTimer documentation and this blog post on "Dangerous Cocoa Calls"
Have you tried the handy debugger tools at your disposal? What happens if you set a breakpoint in your dealloc method? Also, you should post more context around your creation. Is it possible you're creating the timer more than once, thereby replacing the original (but not invalidating it) and leaving it out there to fire at will?