I have the following code which should make drawFrame be called every frame but it doesn't:
- (void)viewDidLoad
{
[super viewDidLoad];
displayLink = [viewReference.window.screen displayLinkWithTarget:(self) selector:#selector(drawFrame)];
[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
- (void) drawFrame:(CADisplayLink*)sender
{
thel.text = #"test";
}
dispayLink is a pointer to CADisplayLink. thel is connected to a label in my view. This view is connected to viewReference. self is the ViewController. drawFrame is declared
- (void) drawFrame:(CADisplayLink*)sender;
thel.text can be set when I test it in viewDidLoad.
It seems drawFrame is never called. The application is based on Xcode 4.2s empty application template with a custom storyboard file (I added it afterwards rather than selecting use storyboard on creation). It is empty besides the view controller, the view and the label.
I'm new to this. When calling [[NSRunLoop currentRunLoop] run] iOS 5.0 Simulator doesn't display the app at all. The currentRunLoop should be the default main runLoop anyway.
Perhaps you need to set the CADisplaylink 'frameInterval' property:
displayLink.frameInterval = someRate (1-60);
Another interesting curiosity is that
weak private var _anim : CADisplayLink? // mysteriously does nothing
display links, for unknown reasons, simply don't run if the variable is weak.
private var _anim : CADisplayLink? // rock on
Related
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!
I have a UITabBarController that nests a UIView-Subclass (ImageViewer) as it's third tab.
In this ImageViewer Subclass I call the viewDidAppear method:
- (void) viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
/* ... start custom code ...
NSLog(#"viewDidAppear tag 1 passed); /* BREAKPOINT 1 here
[myUIActivityIndicator stopAnimating];
NSLog(#"viewDidAppear tag 2 passed); /* BREAKPOINT 2 here
/* ... end custom code ...
}
the method is called automatically, but strangely the view only appears after this method has been processed completely?
When I set breakpoints (1 and 2) as indicated, the processing (upon selecting the tab) stops whilst the previous tab is still showing. Only when clicking continue after the second breakpoint, the view will be displayed. (FYI the NSLogs are carried out immeldiately).
In this case viewDidAppear behaves more like viewWillAppear ....
Any clues what might be going on?
Cheers
If you want to allow the screen to be re-drawn when your view loads, but to trigger some other updating code in -viewDidAppear:, use performSelector:withObject:afterDelay: like this:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self performSelector:#selector(updateUI) withObject:nil afterDelay:0.0];
}
…
- (void)updateUI
{
// Do your UI stuff here
}
When you do it this way, the current event loop will finish quickly, and UIKit will be able to re-draw the screen after your view has loaded. updateUI will be called in the next event loop. This is a good way to get snappy view transitions if you have to perform computationally intensive calculations or updates after a view has loaded.
From the sound of it, if you are actively calling the method, the device might not have time to actually display the view while it is running the "custom code" in your viewDidAppear method. I that case you should let the program call the viewDidAppear method itself.
Your program may also be working on other code which would slow down the appearance of the view, this can be solved using timers. i.e. instead of:
[self otherCode];
you would write:
[NSTimer scheduledTimerWithTimeInterval:.5
target:self
selector:#selector(otherCode)
userInfo:nil
repeats:NO];
you might want to try simply delaying your "custom code" with a timer in this way.
Does any one know when is the best time to stop an NSTimer that is held reference inside of a UIViewController to avoid retain cycle between the timer and the controller?
Here is the question in more details: I have an NSTimer inside of a UIViewController.
During ViewDidLoad of the view controller, I start the timer:
statusTimer = [NSTimer scheduledTimerWithTimeInterval: 1 target: self selector: #selector(updateStatus) userInfo: nil repeats: YES];
The above causes the timer to hold a reference to the view controller.
Now I want to release my controller (parent controller releases it for example)
the question is: where can I put the call to [statusTimer invalidate] to force the timer to release the reference to the controller?
I tried putting it in ViewDidUnload, but that does not get fired until the view receives a memory warning, so not a good place. I tried dealloc, but dealloc will never get called as long as the timer is alive (chicken & egg problem).
Any good suggestions?
You could avoid the retain cycle to begin with by, e.g., aiming the timer at a StatusUpdate object that holds a non-retained (weak) reference to your controller, or by having a StatusUpdater that is initialized with a pointer your controller, holds a weak reference to that, and sets up the timer for you.
You could have the view stop the timer in -willMoveToWindow: when the target window is nil (which should handle the counterexample to -viewDidDisappear: that you provided) as well as in -viewDidDisappear:. This does mean your view is reaching back into your controller; you could avoid reaching in to grab the timer by just send the controller a -view:willMoveToWindow: message or by posting a notification, if you care.
Presumably, you're the one causing the view to be removed from the window, so you could add a line to stop the timer alongside the line that evicts the view.
You could use a non-repeating timer. It will invalidate as soon as it fires. You can then test in the callback whether a new non-repeating timer should be created, and, if so, create it. The unwanted retain cycle will then only keep the timer and controller pair around till the next fire date. With a 1 second fire date, you wouldn't have much to worry about.
Every suggestion but the first is a way to live with the retain cycle and break it at the appropriate time. The first suggestion actually avoids the retain cycle.
One way around it is to make the NStimer hold a weak reference to your UIViewController. I created a class that holds a weak reference to your object and forwards the calls to that:
#import <Foundation/Foundation.h>
#interface WeakRefClass : NSObject
+ (id) getWeakReferenceOf: (id) source;
- (void)forwardInvocation:(NSInvocation *)anInvocation;
#property(nonatomic,assign) id source;
#end
#implementation WeakRefClass
#synthesize source;
- (id)init{
self = [super init];
// if (self) {
// }
return self;
}
+ (id) getWeakReferenceOf: (id) _source{
WeakRefClass* ref = [[WeakRefClass alloc]init];
ref.source = _source; //hold weak reference to original class
return [ref autorelease];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
return [[self.source class ] instanceMethodSignatureForSelector:aSelector];
}
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
[anInvocation invokeWithTarget:self.source ];
}
#end
and you use it like this:
statusTimer = [NSTimer scheduledTimerWithTimeInterval: 1 target: [WeakRefClass getWeakReferenceOf:self] selector: #selector(updateStatus) userInfo: nil repeats: YES];
Your dealloc method gets called (unlike before) and inside it you just call:
[statusTimer invalidate];
You can try with - (void)viewDidDisappear:(BOOL)animated and then you should validate it again in - (void)viewDidAppear:(BOOL)animated
More here
For #available(iOS 10.0, *) you could also use:
Timer.scheduledTimer(
withTimeInterval: 1,
repeats: true,
block: { [weak self] _ in
self?.updateStatus()
}
)
The -viewDidDisappear method may be what you're looking for. It's called whenever the view is hidden or dismissed.
invalidate timer inside - (void)viewWillDisappear:(BOOL)animated did work for me
I wrote a "weak reference" class for exactly this reason. It subclasses NSObject, but forwards all methods that NSObject doesn't support to a target object. The timer retains the weakref, but the weakref doesn't retain its target, so there's no retain cycle.
The target calls [weakref clear] and [timer invalidate] or so in dealloc. Icky, isn't it?
(The next obvious thing is to write your own timer class that handles all of this for you.)
If the timer.REPEAT is set to YES, the owner of the timer (e.g. view controller or view) will not be deallocated until the timer is invalidated.
The solution to this question is to find some trigger point to stop your timer.
For example, I start a timer to play animated GIF images in a view, and the trigger point would be:
when the view is added to the superview, start the timer
when the view is removed from the superview, stop the timer
so I choose the UIView's willMoveToWindow: method as such:
- (void)willMoveToWindow:(UIWindow *)newWindow {
if (self.animatedImages && newWindow) {
_animationTimer = [NSTimer scheduledTimerWithTimeInterval:_animationInterval
target:self selector:#selector(drawAnimationImages)
userInfo:nil repeats:YES];
} else {
[_animationTimer invalidate];
_animationTimer = nil;
}
}
If your timer is owned by a ViewController, maybe viewWillAppear: and viewWillDisappear: are a good place for you to start and stop the timer.
I had exactly the same issue and in the end I decided to override the release method of the View Controller to look for the special case of the retainCount being 2 and my timer running. If the timer wasn't running then this would have caused the release count to drop to zero and then call dealloc.
- (oneway void) release {
// Check for special case where the only retain is from the timer
if (bTimerRunning && [self retainCount] == 2) {
bTimerRunning = NO;
[gameLoopTimer invalidate];
}
[super release];
}
I prefer this approach because it keeps it simple and encapsulated within the one object, i.e., the View Controller and therefore easier to debug. I don't like, however, mucking about with the retain/release chain but I cannot find a way around this.
Hope this helps and if you do find a better approach would love to hear it too.
Dave
EDIT: Should have been -(oneway void)
You can write this code in dealloc function of view controller
for eg.
-(void)dealloc
{
if([statusTimer isValid])
{
[statusTimer inValidate];
[statustimer release];
statusTimer = nil;
}
}
this way the reference counter of statustimer will automatically decrement by 1
& also the data on the allocated memory will also erase
also you can write this code in - (void)viewDidDisappear:(BOOL)animated function
I have a view (splash screen) which displays for two minutes:
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
[viewController showSplash];
}
- (void)showSplash // Show splash screen
{
UIViewController *modalViewController = [[UIViewController alloc] init];
modalViewController.view = modelView;
[self presentModalViewController:modalViewController animated:NO];
[self performSelector:#selector(hideSplash) withObject:nil afterDelay:120.0];
}
I want to add a timer which counts down from 2 minutes to zero to this splash screen.
I imagine I will need to create another view containing the timer. Is this correct? How would I do this and add it to the splash screen, and how would I make the numbers in the timer be displayed on screen in white?
I know two minutes is a very long time to display a splash screen for... but I am just experimenting with various things, there are other things going on for the two minutes!
Many thanks,
Stu
Edit // Ok I now have this:
(.h)
NSTimer *timer5;
UILabel *countDown;
float timeOnSplash;
(.m)
- (void) updateLabel:(NSTimer*)theTimer
{
float timeOnSplash = timeOnSplash - 1;
countDown.text = [NSString stringWithFormat:#"%02d:%02d", timeOnSplash];
}
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
timer5 = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(updateLabel:)
userInfo:nil
repeats:YES];
countDown.text = [NSString stringWithFormat:#"%02d:%02d", timeOnSplash];
}
I get the following uncaught exception when I run the code:
'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key countDown.'
Any ideas?
Edit 2 // Working now, for an excellent solution see TechZen's answer.
Many thanks to all!
NSTimers are unusual objects in that they don't attach to the object that creates them but to the applications NSRunLoop instances. If a timer is one shot, you don't have to retain any reference to it. You should start the timer and forget about it.
In your case you need two track two time intervals (1) the passing of each second so you can update the interface and (2) passing of the two minute interval total.
For (1) you should evoke a repeating timer of one second interval that calls a method in the modalviewcontroller that updates the interface. The best place to evoke the timer would be in the controlller's viewDidAppear method. For (2) you can have property of the controller that stores a value of 159 and then have the method called by the timer decrement it each time the method is called. When it reaches zero, it invalidates the timer.
You should be aware that timers are affected by how quickly the runloop processes all events. If you have intensive background processes that don't pause every few microseconds, the timer may fail to fire on time. If you run into this problem, you should consider creating a separate threads for the splash screen and the configuration.
I do have to wonder why you need display the splash screen for exactly two minutes.
As an aside, the iPhone Human Interface Guidelines expressly state that you should not use splash screens. They can cause your app to be rejected. Using a splash screen that hangs around to long gives the impression that the app or the phone as failed and Apple doesn't like that either.
If you have some heavy duty configuration to do before the app is usable, it is better to create an interface that shows the configuration in process. That way, it is clear that the app is working and not just hung.
Even better, because no one on the move wants to stare at a static iPhone app for two minutes, it's better to get your user started doing something in one thread while the app configures in another. For example, in some kind of url connection, you could start the user typing in some and address of some data while the app makes the connection. For a game, you could have the user select their user name, review high scores, view instructions etc.
You should remember in the design process that people use apps on the iPhone primarily because it saves them time. They don't have drag out a laptop or go to a computer to perform some task. Your app design should focus on getting the user's task performed as quickly as possible. That is true even in the case of a game.
Normally, I would warn against premature optimization but this is kind of big deal.
Edit01:
You want something like this in your splash screen controller.
#interface SplashScreenViewController : UIViewController {
NSInteger countDown;
IBOutlet UILabel *displayTimeLabel;
}
#property NSInteger countDown;
#property(nonatomic, retain) UILabel *displayTimeLabel;
#end
#import "SplashScreenViewController.h"
#implementation SplashScreenViewController
#synthesize countDown;
#synthesize displayTimeLabel;
-(void) viewDidAppear:(BOOL)animated{
countDown=120;
NSTimer *secTimer=[NSTimer timerWithTimeInterval:1.0 target:self selector:#selector(updateCountDown:) userInfo:nil repeats:YES];
}//------------------------------------viewDidAppear:------------------------------------
-(void) updateCountDown:(NSTimer *) theTimer{
NSInteger mins,secs;
NSString *timeString;
countDown--;
if (countDown>=0) {
mins=countDown/60;
secs=countDown%60;
displayTimeLabel.text=[NSString stringWithFormat:#"%02d:%02d",mins,secs];
} else {
[theTimer invalidate];
// do whatever you wanted to do after two minutes
}
}//-------------------------------------(void) updateCountDown------------------------------------
#end
-------
you can call some method every second with NSTimer. there you can change view of your modal ViewController(for example, change text on the label, which will show time). and when your method will be called for the 120 time, you just invalidate your timer
You can use an NSTimer as #Morion suggested. An alternative is the following:
In your #interface file, add the variable:
NSInteger countDown;
then in #implementation:
- (void)showSplash // Show splash screen
{
UIViewController *modalViewController = [[UIViewController alloc] init];
modalViewController.view = modelView;
[self presentModalViewController:modalViewController animated:NO];
countdown = 120;
[self performSelector:#selector(updateTime) withObject:nil afterDelay:1.0];
}
- (void)updateTime {
//decrement countDown
if(--countDown > 0){
//
// change the text in your UILabel or wherever...
//
//set up another one-second delayed invocation
[self performSelector:#selector(updateTime) withObject:nil afterDelay:1.0];
}else{
// finished
[self hideSplash];
}
}
Yes, one way would be to create a new view which has a transparent background ([UIColor clearColor]) and a label with white text. Just call [modalViewController.view addSubview:timerView] to add it as a subview/overlay.
I'm not sure how much help you need with actually creating the views and setting up the label etc.
I tried to create a SplashView which display the Default.png in the background and a UIProgressBar in front. But the splash screen is not being updated...
Inside my view controller I load first the splash view with a parameter how many steps my initialisation has and then I start a second thread via NSTimer and after each initialisation step I tell the SplashView to display the new progress value.
All looks good in theory, but when running this app the progress bar is not being updated (the method of the splash screen receives the values, I can see it in the logs). I also tried to add usleep(10000); in between to give the view updates a bit time and also instead of using the progress bar I drew directly on the view and called [self setNeedsDisplay]; but all didn't work :/
What am I doing wrong?
Thanks for your help!
Tom
Here is some code:
SPLASHSCREEN:
- (id)initWithFrame:(CGRect)frame withStepCount:(int)stepCount {
if (self = [super initWithFrame:frame]) {
// Initialization code
background = [[UIImageView alloc] initWithFrame: [self bounds]];
[background setImage: [UIImage imageWithContentsOfFile: [NSString stringWithFormat:#"%#/%#", [[NSBundle mainBundle] resourcePath], #"Default.png"]]];
[self addSubview: background];
progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
[progressView setFrame:CGRectMake(60.0f, 222.0f, 200.0f, 20.0f)];
[progressView setProgress: 0.0f];
stepValue = 1.0f / (float)stepCount;
[self addSubview:progressView];
}
return self;
}
- (void)tick {
value += stepValue;
[progressView setProgress: value];
}
VIEWCONTROLLER:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
splashView = [[SplashView alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 320.0f, 480.0f) withStepCount:9];
[self setView: splashView];
NSTimer* delayTimer;
delayTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:#selector(finishInitialization) userInfo:nil repeats:NO];
}
return self;
}
- (void)finishInitialization {
// do some stuff, like allocation, opening a db, creating views, heavy stuff...
[splashView tick]; // this should update the progress bar...
// do some stuff, like allocation, opening a db, creating views, heavy stuff...
[splashView tick]; // this should update the progress bar...
// init done... set the right view and release the SplashView
}
As mentioned in another answer, for some finite amount of time, as your app is being launched, Default.png is displayed and you have no control over it. However, if in your AppDelegate, you create a new view that displays the same Default.png, you can create a seamless transition from the original Default.png to a view that you can add a progress bar to.
Now, presumably, you have created a view or similar and you are updating a progress bar every so often in order to give the user some feedback. The challenge here is that your view is only drawn when it gets called to do a drawRect. If, however, you go from AppDelegate to some initialization code to a viewcontroller's viewDidLoad, without the run loop getting a chance to figure out which views need to have drawRect called on, then your view will never display its status bar.
Therefore in order to accomplish what you want, you have to either make sure that drawRect gets called, such as by pushing off a lot of your initialization code into other threads or timer tasks, or you can force the drawing by calling drawRect yourself, after setting up contexts and such.
If you go with the background tasks, then make sure your initialization code is thread-safe.
Default.png is just a graphic, a static image shown while the application is launching. If you want to show further progress, you'll have to show everything at the applicationDidLaunch phase. Show your modal "Splash Screen" there first (Create a view controller, add its view as a subview of your main window) and dismiss it when you are done whatever additional loading you needed to do.
Also, you need to do update your progress bar in a seperate thread. Updating your GUI in the same thread where a lot of business is going on is (in my opinion, but I could be wrong) a bad idea.
The main thread is, as far as I know, the only one that can safely do GUI things, and its event loop (that is, the main application thread's) is the one that does the actual displaying after you've called -setNeedsDisplay. Spawn a new thread to do your loading, and update the progress on the main thread.