This animation is not functioning in this method - objective-c

I'm having a lot of trouble figuring this one out. This method is imported from another class into my viewController.m It works fine if I copy the code into an IBAction in the same file. And the "test midi" is logging when it is supposed to. So the IBOutlets and animation code seem OK but for some reason this method does not do what it is supposed to
- (void) source:(theSource*)data dataReceived:(const dataList *)theList
{
led.animationImages = [NSArray arrayWithObjects:[UIImage imageNamed:#"led-highlighted.png"],[UIImage imageNamed:#"led-passive.png"],nil];
led.animationDuration = 0.3;
led.animationRepeatCount = 20;
[led startAnimating];
NSLog(#"test");}
it also doesn't work if I simply put this to swap the image. The method is being called because it is logging to console.
midiLed.image = [UIImage imageNamed:# "led-highlighted.png"];

The problem may lie in how you are calling this method. It should be on the main thread, and after calling it, your code should return to the run loop (i.e. your code should be "done") before changes to the user interface will have effect.
If this doesn't help you find it, please share the code calling this method.

What thread is -source:dataReceived: being called on? If you're using CoreMIDI, your MIDI-received function will get called on a separate, high-priority thread.
You should not touch the UI from a non-main thread, because UIKit isn't thread safe.
Here's one way to get the UI running on the main thread:
- (void) source:(theSource*)data dataReceived:(const dataList *)theList
{
dispatch_async(dispatch_get_main_queue(), ^{
led.animationImages = [NSArray arrayWithObjects:[UIImage imageNamed:#"led-highlighted.png"],[UIImage imageNamed:#"led-passive.png"],nil];
led.animationDuration = 0.3;
led.animationRepeatCount = 20;
[led startAnimating];
NSLog(#"test");
});
}

Related

How to switch between background and main threads

I've never used background threads before. I have a time consuming computation currently running on the main thread which appends the data output to a TERecord. My workflow essentially goes:
run long process…
update GUI…
run long process…
update GUI…
and so on.
At several places where the code produces (string) output I update the UI by calling my 'addToRecord' method shown here:
-(void)addToRecord:(NSString*)passedStr:(BOOL)updateUI
{
NSRange endRange;
// add the passed text...
endRange.location = [[theOutputView textStorage] length];
endRange.length = 0;
[theOutputView replaceCharactersInRange:endRange withString:passedStr];
if(updateUI) // immediate GUI update needed...
{
// scroll window contents to BOTTOM of page...
endRange = NSMakeRange([[theOutputView string] length],0);
[theOutputView scrollRangeToVisible:endRange];
[theOutputView display];
}
}
While it does the job, my entire UI remains unresponsive until the process completes, of course. I know I should be doing the heavy lifting on a background thread which I've never used before. I've figured out part of the problem in creating a background thread like below:
-(IBAction)readUserInput:(id)sender
{
// irrelevant code snipped for brevity
if([self checkForErrors] == NO)
{
[runButton setEnabled:NO];
[self performSelectorInBackground:#selector(runWorkThread) withObject:nil];
}
}
-(void)runWorkThread
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
[self runLongProcess];
[pool drain];
}
but i just don't understand how to call the main thread every time the code encounters my 'addToRecord' method, then how to return control to the background thread?
Another possibility might be to remove the updateUI code from my 'addToRecord' method and just have have the main thread calling this code every second or so on a timer?
Any advice and sample code would be greatly appreciated. Thanks!
Instead of using performSelectorInBackground you can use the Dispatch framework (also called GCD), which is the preferred way of handling concurrent work. The Dispatch already has a pool of background threads set up that you can use. To switch thread you call dispatch_async() like this:
dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{
// :
// Do your background work here
// :
dispatch_async(dispatch_get_main_queue(), ^{
// :
// Now you are back in the main thread
// :
});
});
The first parameter is the queue identifier which is supplied to you by either dispatch_get_global_queue() which returns one of the "worker" queues, or dispatch_get_main_queue() which returns the main queue. The last parameter is a code block that is executed on the selected queue.
When requesting a concurrent queue using dispatch_get_global_queue() you specify a Quality of Service, which determines the priority your code will have in relation to other work. See the documentation for more information and possible values.
Read more on the Dispatch

OCMock in a block context

So I am attempting to throw together a simple test to verify that I am receiving frequency values from my audioController correctly.
In my view I am making a call like this to setup up a block callback:
- (void) registerVolumeCallback {
NSNumberBlock frequencyCallback = ^(NSNumber *frequency) {
self.currentFrequency = frequency;
};
self.audioController.frequencyCallback = frequencyCallback;
}
In my audio controller the frequency callback block is called with an nsnumber containing the frequency.
In my tests file I have the following:
- (void) testFrequencyAudioServiceCallbackActive {
OCMockObject *mockEqualizer = [OCMockObject partialMockForObject:self.testEqualizer];
[[[mockEqualizer stub] andCall:#selector(mockDidUpdateFrequency:)
onObject:self] setCurrentFrequency:[OCMArg any]];
[self.testEqualizer startAnimating];
[ mockEqualizer verify];
}
And:
- (void) mockDidUpdateFrequency: (NSNumber *) frequency {
GHAssertTrue((frequency!= nil), #"Audio Service is messing up");
}
Where test equalizer is an an instance of the aforementioned view. So Im trying to do some swizzling here. Problem is, mockDidUpdateFrequency is never called. I tried putting:
self.currentFrequency = frequency;
outside of the block, and the swizzling does happen and I do get a call to mockDidUpdateFrequency. I also tried:
- (void) registerVolumeCallback {
__block UIEqualizer *blockSafeSelf = self;
NSNumberBlock frequencyCallback = ^(NSNumber *frequency) {
blockSafeSelf.currentFrequency = frequency;
};
self.audioController.frequency = frequencyCallback;
}
No luck. Some weird instance stuff is going on here in the block context that I am not aware of. Anyone know whats happening?
You'll need to provide some more details for a definitive answer. For example, how is registerVolumeCallback invoked? And is frequencyCallback your own code, or a third-party API?
With what you've provided, I suspect that frequencyCallback is an asynchronous call. So even though startAnimating might create the condition where it will eventually be invoked, you immediately verify the mock before the callback has had a chance to be invoked. To get your test to do what you want as written, you need to understand what queue that block is executed on, and you need to give it a chance to execute.
If it's invoked asynchronously on the main queue, you can let the main run loop spin before calling verify:
[self.testEqualizer startAnimating];
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:.1]];
[mockEqualizer verify];
If it's invoked on a different queue, you have some different options, but it would help to have a clearer picture how your code is structured first.

Updating UIAlertView with progress of background thread

XCode 4.5, iPad development, iOS6
Hi, I hope you can help a novice developer! Apologies in advance if this has already been answered but I could not find during my searches!
I am developing an app that needs to import a large amount of data into Core Data. The import routine works fine (alert shows 'Please wait' with activity monitor while routine works in the background) but I want to give the users more detailed feedback on the progress of the import (such as 'XX% imported'). The following code kicks the process off and -
- (IBAction)import:(id)sender{
[self showWaiting];
[self performSelectorInBackground:(#selector(callGrouper)) withObject:nil];
}
-(void)showWaiting{
alertMsg = #"Please Wait....";
waitAlert = [[UIAlertView alloc] initWithTitle:alertMsg message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
[waitAlert show];
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
indicator.center = CGPointMake(waitAlert.bounds.size.width / 2, waitAlert.bounds.size.height - 50);
[indicator startAnimating];
[waitAlert addSubview:indicator];
}
-(void)callGrouper{
ImportRoutine *firstTest = [[ImportRoutine alloc] init];
[firstTest runImport:managedObjectContext];
[waitAlert dismissWithClickedButtonIndex:0 animated:TRUE];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle: #"iPad Application"
message: #"Import complete!"
delegate: self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
}
Within ImportRoutine (separate class) I have code that gathers data on percentage imported but how can I pass this message back to the main thread so I can update 'alertMsg' and in turn update the UIAlertView?
You can dispatch blocks of code back onto the main thread using GCD (grand central dispatch):
dispatch_async(dispatch_get_main_queue(), ^{
// code here to update UI
});
Any object in the scope of the method that contains the dispatch call gets retained which makes it easy to pass objects back into the main thread without worrying about the background thread being deallocated along with its objects before you've had a chance to process the data. Primitive values in the local scope (aka int, float, double, etc) are copied, so if you set an int to 5, dispatch a block where you print the value of the int, and then right after set the int to 10, even if the block executes after you set the int to 10 it'll still print 5. Note that You can't mutate the same mutable object (such as `NSMutableArray or NSMutableDictionary) in two threads at the same time or mutate in one and enumerate in another without crashing so you'll want to be careful about doing something like that (thanks goes to #andrewmadsen for reminding me to warn you).
dispatch_async(), unlike dispatch_sync(), will not wait for the code that's dispatched to complete before continuing execution which is nice since your background thread doesn't need to care if things in the UI have finished.
You could stick the dispatch call inside of the method on the ImportRoutine class that calculates the progress as long as your UIAlertView is addressable outside of your view controller class. Or if you want to follow model-view-controller design principals more closely, you could create a method like so in your view controller:
- (void)updateProgressToPercentComplete:(double)percent {
if ([NSThread currentThread] != [NSThread mainThread]) {
dispatch_async(dispatch_get_main_queue(), ^{
// update code or call to method that is guaranteed to be on the main thread.
}
}
else {
// update code or call to method that is guaranteed to be on the main thread.
}
}
If you've gone into the documentation and now you're all like "oh my gosh Objective-C blocks are the coolest thing ever" you could modify the method above so you don't need to write the same update code twice:
- (void)updateProgressToPercentComplete:(double)percent {
void (^updateProgressBlock)(void) = ^{
// update code
};
if ([NSThread currentThread] != [NSThread mainThread]) {
dispatch_async(dispatch_get_main_queue(), updateProgressBlock());
}
else {
updateProgressBlock();
}
}
By the way I noticed in your -callGrouper code that you're using an existing managedObjectContext that I assume you created on the main thread in a background thread... most of core data isn't threadsafe so you need to be extremely careful or you will crash all over the place. You might be better off creating a secondary managed object context on the background thread and then merging changes into the context on the main thread (or save on the background thread and re-fetch on the main thread).
Edit:
Basic flow: Begin your background process from your view controller and pass in a progress block. -> Import class in the background thread executes your progress block periodically -> Inside your progress block you dispatch back to the main thread to update UI.
In your ImportRoutine class add a property declaration like so:
#property (nonatomic, strong) void (^progressBlock)(NSUInteger);
Which means a property called progressBlock that takes an unsigned integer (0-100) and doesn't return anything (void). You should make this property private by using a class extension.
Then you'll want to create a method in your import class like so:
- (void)callGrouper:(void (^)(NSUInteger))progress {
[self setProgressBlock:progress];
// Your import code
}
In your method where you receive progress updates, call the progressBlock and pass in your progress as a number between 0 and 100:
if ([self progressBlock] != nil) {
[self progressBlock](progressValue);
}
Notice that I check to make sure the progress block isn't nil. You would crash and burn if you tried to execute a NULL block.
Then you can pass in a block as the object in your import routine call you already have in the view controller and inside the block dispatch back to the main queue and update your progress.
You can use:
[self performSelectorOnMainThread:#selector(yourSelector) withObject:anObjectIfYouNeedToSendOne waitUntilDone:YES/NO];
The UI runs on main thread and so you cand acces again your UIAlertView or other UI object.

Async call in Objective-C

I'm trying to get data from a website- xml. Everything works fine.
But the UIButton remains pressed until the xml data is returned and thus if theres a problem with the internet service, it can't be corrected and the app is virtually unusable.
here are the calls:
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if(!appDelegate.XMLdataArray.count > 0){
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[appDelegate GetApps]; //function that retrieves data from Website and puts into the array - XMLdataArray.
}
XMLViewController *controller = [[XMLViewController alloc] initWithNibName:#"MedGearsApps" bundle:nil];
[self.navigationController pushViewController:controller animated:YES];
[controller release];
}
It works fine, but how can I make the view buttons functional with getting stuck. In other words, I just want the UIButton and other UIButtons to be functional whiles the thing works in the background.
I heard about performSelectorInMainThread but I can't put it to practice correctly.
You don’t understand the threading model much and you’re probably going to shoot yourself in the foot if you start adding asynchronous code without really understanding what’s going on.
The code you wrote runs in the main application thread. But when you think about it, you don’t have to write no main function — you just implement the application delegate and the event callbacks (such as touch handlers) and somehow they run automatically when the time comes. This is not a magic, this is simply a Cocoa object called a Run Loop.
Run Loop is an object that receives all events, processes timers (as in NSTimer) and runs your code. Which means that when you, for example, do something when the user taps a button, the call tree looks a bit like this:
main thread running
main run loop
// fire timers
// receive events — aha, here we have an event, let’s call the handler
view::touchesBegan…
// use tapped some button, let’s fire the callback
someButton::touchUpInside
yourCode
Now yourCode does what you want to do and the Run Loop continues running. But when your code takes too long to finish, such as in your case, the Run Loop has to wait and therefore the events will not get processed until your code finishes. This is what you see in your application.
To solve the situation you have to run the long operation in another thread. This is not very hard, but you’ll have to think of a few potential problems nevertheless. Running in another thread can be as easy as calling performSelectorInBackground:
[appDelegate performSelectorInBackground:#selector(GetApps) withObject:nil];
And now you have to think of a way to tell the application the data has been loaded, such as using a notification or calling a selector on the main thread. By the way: storing the data in the application delegate (or even using the application delegate for loading the data) is not very elegant solution, but that’s another story.
If you do choose the performSelectorInBackground solution, take a look at a related question about memory management in secondary threads. You’ll need your own autorelease pool so that you won’t leak autoreleased objects.
Updating the answer after some time – nowadays it’s usually best to run the code in background using Grand Central Dispatch:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// No explicit autorelease pool needed here.
// The code runs in background, not strangling
// the main run loop.
[self doSomeLongOperation];
dispatch_sync(dispatch_get_main_queue(), ^{
// This will be called on the main thread, so that
// you can update the UI, for example.
[self longOperationDone];
});
});
Use NSURLConnection's connectionWithRequest:delegate: method. This will cause the specified request to be sent asynchronously. The delegate should respond to connection:didReceiveResponse: and will be sent that message once the response is completely received.
You can make use of a background operation that gets pushed into the operation queue:
BGOperation *op = [[BGOperation alloc] init];
[[self operationQueue] addOperation:op];
[op release];
I've created specific "commands" that get executed in the background:
#implementation BGOperation
# pragma mark Memory Management
- (BGOperation *)init
{
if ((self = [super init]) != nil)
/* nothing */;
return self;
}
- (void)dealloc
{
self.jobId = nil;
[super dealloc];
}
# pragma mark -
# pragma mark Background Operation
- (void)main
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[appDelegate GetApps];
[pool release];
return;
}
#end
After completion it might be a good idea to send a notification to the main thread because the internal database has been changed.
It looks as if you might be using NSURLConnection inside your getApps method. If so, you should convert it to an asynchronous call.

How do I update a progress bar in Cocoa during a long running loop?

I've got a while loop, that runs for many seconds and that's why I want to update a progress bar (NSProgressIndicator) during that process, but it updates only once after the loop has finished. The same happens if I want to update a label text, by the way.
I believe, my loop prevents other things of that application to happen. There must be another technique. Does this have to do with threads or something? Am I on the right track? Can someone please give me a simple example, how to “optimize” my application?
My application is a Cocoa Application (Xcode 3.2.1) with these two methods in my Example_AppDelegate.m:
// This method runs when a start button is clicked.
- (IBAction)startIt:(id)sender {
[progressbar setDoubleValue:0.0];
[progressbar startAnimation:sender];
running = YES; // this is a instance variable
int i = 0;
while (running) {
if (i++ >= processAmount) { // processAmount is something like 1000000
running = NO;
continue;
}
// Update progress bar
double progr = (double)i / (double)processAmount;
NSLog(#"progr: %f", progr); // Logs values between 0.0 and 1.0
[progressbar setDoubleValue:progr];
[progressbar needsDisplay]; // Do I need this?
// Do some more hard work here...
}
}
// This method runs when a stop button is clicked, but as long
// as -startIt is busy, a click on the stop button does nothing.
- (IBAction)stopIt:(id)sender {
NSLog(#"Stop it!");
running = NO;
[progressbar stopAnimation:sender];
}
I'm really new to Objective-C, Cocoa and applications with a UI. Thank you very much for any helpful answer.
If you are building for Snow Leopard, the easiest solution is in my opinion to use blocks and Grand Central Dispatch.
The following code shows you how your startIt: method would look like when using GCD.
Your stopIt: method should work fine as you wrote it. The reason why it wasn't working before is that mouse events happen on the main thread and thus the button didn't respond to you because you were doing work on the main thread. This issue should have been resolved now as the work has been put on a different thread now with GCD. Try the code, and if it doesn't work, let me know and I will see if I made some errors in it.
// This method runs when a start button is clicked.
- (IBAction)startIt:(id)sender {
//Create the block that we wish to run on a different thread.
void (^progressBlock)(void);
progressBlock = ^{
[progressbar setDoubleValue:0.0];
[progressbar startAnimation:sender];
running = YES; // this is a instance variable
int i = 0;
while (running) {
if (i++ >= processAmount) { // processAmount is something like 1000000
running = NO;
continue;
}
// Update progress bar
double progr = (double)i / (double)processAmount;
NSLog(#"progr: %f", progr); // Logs values between 0.0 and 1.0
//NOTE: It is important to let all UI updates occur on the main thread,
//so we put the following UI updates on the main queue.
dispatch_async(dispatch_get_main_queue(), ^{
[progressbar setDoubleValue:progr];
[progressbar setNeedsDisplay:YES];
});
// Do some more hard work here...
}
}; //end of progressBlock
//Finally, run the block on a different thread.
dispatch_queue_t queue = dispatch_get_global_queue(0,0);
dispatch_async(queue,progressBlock);
}
You can try this code ..
[progressbar setUsesThreadedAnimation:YES];
I believe, my loop prevents other things of that application to happen.
Correct. You need to break this up somehow.
One way would be a timer, with you whittling away the queue a little at a time in the timer callback. Another would be to wrap the code to handle one item in an NSOperation subclass, and create instances of that class (operations) and put them into an NSOperationQueue.
Does this have to do with threads or something?
Not necessarily. NSOperations run on threads, but the NSOperationQueue will handle spawning the thread for you. A timer is a single-threaded solution: Every timer runs on the thread you schedule it on. That can be an advantage or a disadvantage—you decide.
See the threads section of my intro to Cocoa for more details.
This worked for me, which is a combination of answers from others that did not seem to work (for me at least) on their own:
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
//do something
dispatch_async(dispatch_get_main_queue(), ^{
progressBar.progress = (double)x / (double)[stockList count];
});
//do something else
});