I'm working on a project, where i have to update the text of a UILabel really regularly (0.085f). So, I insert the update of the label in a loop like this :
MetresNumber = MetresNumber + 0.25;
DisplayMetres.text = [NSString stringWithFormat:#"%07.0f", MetresNumber];
I precise that "MetresNumber" is a float, and "DisplayMetres" the UILabel.
And this sort of code really really makes bad performances ! It's incredible how slower it goes since i've added those lines.
I made some searches, and found elements like :
[DisplayMetres setNeedsDisplay];
But it didn't change and update the text on the label.
It's in a loop called with :
timer = [NSTimer scheduledTimerWithTimeInterval:0.085 target:self selector:#selector(myLoop) userInfo:nil repeats:YES];
So my question is, could my code be improve, to get better performances, or should i forget my UILabel because it's too slow with ?
Thanks !
(void)setNeedsLayout
Call this method on your application’s main thread when you want to adjust the layout of a view’s subviews. This method makes a note of the request and returns immediately. Because this method does not force an immediate update, but instead waits for the next update cycle, you can use it to invalidate the layout of multiple views before any of those views are updated. This behavior allows you to consolidate all of your layout updates to one update cycle, which is usually better for performance.
Another problem is that a scheduledTimer will not get called while the main thread is tracking touches. You need to schedule the timer in the main run loop.
So instead of doing
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(updateLabel:) userInfo:nil repeats:YES];
use
NSTimer* timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:#selector(updateLabel:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
Also Use Timer selector method like below:
- (void) updateLabel:(id) sender {
MetresNumber = MetresNumber + 0.25;
NSString *text = [NSString stringWithFormat:#"%07.0f", MetresNumber];
dispatch_sync(dispatch_get_main_queue(), ^{
DisplayMetres.text = text;
});
}
There shouldn't be any performance issues when you are just updating a single label every 85ms. First find out what actually causes the lags. Use the Time Profiler instrument.
I think most time will be spent on the string drawing.
Here are some tips how you can optimize your code:
You don't need to call setNeedsLayout or setNeedsDisplay explicitely on the label. Just set the text property (on the main thread of course).
The resulting string in your code will always be a 7-digit integer. Consider using an integer instead of a float. Formatting an integer will be faster.
stringWithFormat can be slow sometimes. You could try using a NSNumberFormatter or simply generate the string with: [#(MetresNumber) stringValue]
In your code the string actually doesn't change everytime the timer fires. Only every 4th time. You can set the time interval to 4*0.085 and replace MetresNumber = MetresNumber + 0.25 with MetresNumber = MetresNumber + 1.
Try using this custom UILabel class
Don't use UILabel at all. Use pre-drawn images for each digit.
Schedule the timer with NSRunLoopCommonModes (see answer from Lightygalaxy)
Related
I have surfed on a bunch of resources from the internet but still couldn't get any idea of what I'm trying to implement.
I would like to record user preferences by detecting how much time they have stayed in each information pages.
In order to make this question simpler, that says I have a entrance page with 5 different theme pages which represent different information.
I would like to know which page is the page that user most interesting.
What I wish to do is to put a counter in each theme pages and calculate how much time they stay in that page (the counter should be able to pause for reentrance), and then when I press a button on the entrance page, an alert will tell me which page is the page that user spent most of time on it.
I hope this make sense!
Does anyone have any experience on this? I would be most appreciative if anyone can provide some codes and examples for me.
ViewController A:
- (void)viewDidLoad {
[super viewDidLoad];
//create iVar of NSInteger *seconds
seconds = 0;
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:#selector(increaseTimeCount) userInfo:nil repeats:YES];
[timer fire];
}
- (void)increaseTimeCount {
seconds++;
}
- (void)dealloc {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// you can add to array too , if you want and get average of all values later
[defaults setInteger:seconds forKey: NSStringFromClass(self)];
}
now in Entrance View ..
get the time as
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger *secondsInView = [defaults integerForKey:NSStringFromClass(View1ClassName)];
Firstly I'd like to draw your attention to the Cocoa/CF documentation (which is always a great first port of call). The Apple docs have a section at the top of each reference article called "Companion Guides", which lists guides for the topic being documented (if any exist). For example, with NSTimer, the documentation lists two companion guides:
Timer Programming Topics for Cocoa
Threading Programming Guide
For your situation, the Timer Programming Topics article is likely to be the most useful, whilst threading topics are related but not the most directly related to the class being documented. If you take a look at the Timer Programming Topics article, it's divided into two parts:
Timers
Using Timers
For articles that take this format, there is often an overview of the class and what it's used for, and then some sample code on how to use it, in this case in the "Using Timers" section. There are sections on "Creating and Scheduling a Timer", "Stopping a Timer" and "Memory Management".There are a couple of ways of using a timer. From the article, creating a scheduled, non-repeating timer can be done something like this:
1) scheduled timer & using selector
NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 2.0
target: self
selector:#selector(onTick:)
userInfo: nil repeats:NO];
if you set repeats to NO, the timer will wait 2 seconds before
running the selector and after that it will stop;
if repeat: YES, the timer will start immediatelly and will repeat
calling the selector every 2 seconds;
to stop the timer you call the timer's -invalidate method: [t
invalidate]; As a side note, instead of using a timer that doesn't
repeat and calls the selector after a specified interval, you could
use a simple statement like this:
[self performSelector:#selector(onTick:) withObject:nil afterDelay:2.0];
this will have the same effect as the sample code above; but if you want to call the selector every nth time, you use the timer with repeats:YES;
2) self-scheduled timer
NSDate *d = [NSDate dateWithTimeIntervalSinceNow: 60.0];
NSTimer *t = [[NSTimer alloc] initWithFireDate: d
interval: 1
target: self
selector:#selector(onTick:)
userInfo:nil repeats:YES];
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:t forMode: NSDefaultRunLoopMode];
[t release];
this will create a timer that will start itself on a custom date
specified by you (in this case, after a minute), and repeats itself
every one second
3) unscheduled timer & using invocation
NSMethodSignature *sgn = [self methodSignatureForSelector:#selector(onTick:)];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn];
[inv setTarget: self];
[inv setSelector:#selector(onTick:)];
NSTimer *t = [NSTimer timerWithTimeInterval: 1.0
invocation:inv
repeats:YES];
and after that, you start the timer manually whenever you need like this:
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer: t forMode: NSDefaultRunLoopMode];
And as a note, onTick: method looks like this:
-(void)onTick:(NSTimer *)timer {
//do smth
}
Try this simple method:
- (void)viewDidLoad
{
[super viewDidLoad];
count = 0; // Declare int * count as global variable;
[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:#selector(timerAction) userInfo:nil repeats:YES];
}
- (void)timerAction
{
[self custom_method:count++]
}
Might I suggest a different route. If you take the time since reference date, when the user enters the page:
NSTimeINterval time = [NSDate timeIntervalSinceReferenceDate]
then do the same when they leave the page and compare them.
timeOnPage = time - time2;
This is much more efficient than firing a timer on another thread unnecessary.
You do not need to use NSTimers for this at all.
Store the date/time when the user starts viewing, and calculate the time difference when they stop viewing using simple time arithmetic.
Exactly As Dave Wood says You should use date and time for starting and ending viewing that screen and calculate the difference and then save it to any integer variable.Using NSTimer will make the performance effect in your app and make the compiler busy while incrementing the count.
Everytime I am finished with my NSTimer, I want to invalidate it and create a new interval but it keeps the old interval as well as new interval. I want to invalidate NSTimes once I click the offButton. The timer stops printing "Working" but when I call my method with a different interval, it prints "Working" for both intervals.
My code is something like this:
-(void) fireTimer{
NSString *textValue = [sliderLabel text];
float value = [textValue floatValue];
[NSTimer scheduledTimerWithTimeInterval:value target:self selector:#selector(vibrate:) userInfo:nil repeats:YES];
}
- (void) vibrate:(NSTimer*)timer {
if(_offButton.selected){
[timer invalidate];
timer=nil;
}
NSLog(#"Working");
}
You aren't following the MVC design pattern by getting your values directly from the UITextField. Those values should be stored in a model object, with the MVC pattern being used to get any new values from the text field into the model. Your current implementation is very delicate and will break in the slightest breeze. It also requires this code to have access to the UI elements, which is very inflexible; it will be better to give it access to just the model object.
Store the NSTimer * as an instance variable, and note that if you are using ARC then the NSTimer retains the target (!!) so make this instance variable __weak to break the retain-cycle.
If you want your timer to repeat then there is no need to reset it at all; this only needs to be done if the user changes the time (see point 1!).
Move the if (button_selected) do_vibrate; code into the timer fired method.
The invalidation code that you use itself is correct. But it would be easier for you to keep a reference to your timer as an ivar or property.
In that case you would definetly avoid making multiple instances of a timer.
Is there any method for slide show of an array of strings in UILabel in iphone app?(ie, strings will appear one by one). Anyone please help me.
Look at NSTimer.
This can get you a repeated callback every X seconds. You can use this to swap the strings in an array.
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(swapStrings:) userInfo:nil repeats:YES];
_myStrings = #[ #"a" , #"b", ..... ];
...
- (void) swapStirings:(id)sender
{
myInt ++;
if (myInt >= [_myStrings count]) myInt = 0;
myLabel.text = [_myStrings objectAtIndex:myInt];
}
No, there is not. But, the good news it should be trivial to implement. I suggest creating a subclass of uilabel that has an array of strings as an ivar. The subclass has an init method that sets the array and a time interval. Then it uses an nstimer to change its label and redisplay itself. Good luck!
Is there any method (like – viewDidLoad) to continuously execute a part of code? I need to be able to check a value on a remote server continuously.
The way you would do this is to set up an NSTimer.
-(void)startCheckingValue
{
mainTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:#selector(checkValue:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:mainTimer forMode:NSDefaultRunLoopMode];
}
-(void)checkValue:(NSTimer *)mainTimer
{
//Placeholder Function, this is where you write the code to check your value on the remote server
}
The timerWithTimeInterval function is the one that you are interested in, the main things that you need to pass it, as you see above, are the interval at which it will execute the function whose selector you pass it. The time interval is in seconds, so it is currently set to check every second, which is probably way too fast.
Use an NSTimer to execute the same block of code every x seconds. However, I don't think that's what you want, given that it would put a lot of extra load on the server and you might get banned, so there's probably a better way.
apple's page on NSTimer use
You ned to use NSTimer For this:
in your interface declare a NSTimer object like:
NSTimer *timer;
in your .m viewDidLoad method add the below line.
timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(timerFireMethod:) userInfo:nil repeats:YES];
In the timerFireMethod method you need to do the server calling and other stuffs.
I have a view-based template app and have UILabel & UIButton. For debugging purposes I'm showing and hiding the button whilst changing the UILabel.text.
In C++ I would 'thread root();' to execute the root method but I don't know how to in Objective-c. How to run my 'root' method once the view loads?
-(void) root
{
[bombButton1 setHidden:NO];
int s = 0;
int j = 10;
while ( s < j )
{
[bombButton1 setHidden:YES];
NSString *debugLabelString = [NSString stringWithFormat:#"%d", s];
debugLabel.text=debugLabelString;
s++;
}
Edit:
Right, now I have: (but I get ERROR: Expected method body on the "-(void) rootMethod: NSTimer * timer {" line)
-(void) applicationDidFinishLaunching : (UIApplication *) application {
spawnTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:#selector(rootMethod:) userInfo:nil repeats: YES];
}
-(void) rootMethod: NSTimer * spawnTimer {
int s = 0;
int j = 10;
while ( s < j )
{
NSString *debugLabelString = [NSString stringWithFormat:#"%d", s];
debugLabel.text=debugLabelString;
//debugLabel.text=#"debug test complete";
s++;
}
}
Several ways to do this, I think. Here's one:
[self performSelectorInBackground:#selector(root) withObject:nil];
You'd make this call in say, your -(void)viewDidAppear: method.
You may run into issues running code on threads other than the main thread that tries to manipulate the UI.
That sleep(1) is worrisome. You could use a repeating NSTimer instead and eliminate the sleep(1) entirely. Something like:
[NSTimer scheduledTimerWithInterval:2.0 target:self
selector:#selector(root:) userInfo:nil repeats:YES];
For NSTimer, you'd have to change your method, root, to have a signature like
- (void)root:(NSTimer*)theTimer
You need to implement a called viewDidLoad.
- (void) viewDidLoad() {
// your code here
}
I'm sure you have your reasons, but you really shouldn't iteract with UI components in anything other than the UI thread. What you actually need to do is use an NSTimer to call a method on the UI thread multiple times.
What you should be doing is performSelectorOnMainThread when you want to update the UI Thread.
Do your running in the background and update variables that will contain the updated values, then use performSelectorOnMainThread on the View, sending it to a method that will merely update the Textbox with the data in the variables.
You can do anything in a background thread, except update the ui.
Edit: Furthermore I dont recommend using Timers in place of background threads, I have had instances when using Timers, where only so many get created and when I expected a background thread to fire, it never did. The timer actually never fired, even tho it was created.