what are the difference between blocks and functions in iphone - iphone

double(^simpleBlock)(double,int, double ) = ^(double n3,int n1,double n2){
NSLog(#"Block with Three parameter");
return n1*n2*n3;
};
what are the difference between blocks and functions in iphone.Which one is better.

Block is used for doing work on background thread.

Related

Process Live Photos on multiple threads

I am processing a PHLivePhoto using .frameProcessor to modify each frame. The frames appear to be processed in sequence, which is slow. Can I get PHLivePhotoEditingContext.frameProcessor to take advantage of more than one core?
func processLivePhoto(input: PHContentEditingInput) {
guard let context = PHLivePhotoEditingContext(livePhotoEditingInput: input)
else { fatalError("not a Live Photo editing input") }
context.frameProcessor = { frame, _ in
let renderedFrame = expensiveOperation(using: frame.image)
return renderedFrame
}
// ...logic for saving
}
I'm afraid there's no way to parallelize the frame processing in this case. You have to keep in mind:
Video frames need to be written in order.
The more frames you would process in parallel, the more memory you would need.
Core Image is processing the frames on the GPU, which can usually only process one frame at a time anyways.
Your expensiveOperation is not really happening in the frameProcessor block anyways, since the actual rendering is handled by the framework outside this scope.

GtkApplicationWindow subclass "destroy" twice

I took the application1 from examples in Gtk source
and modified GtkApplicationWindow subclass as to save some window state in the "destroy" signal handler. The problem with my code is that the save_some_state() is called twice. Why? How can I fix it?
static void
example_app_activate (GApplication *app) {
ExampleAppWindow *win;
win = example_app_window_new (EXAMPLE_APP (app));
gtk_window_present (GTK_WINDOW (win));
}
........
static void
on_app_window_destroy (GtkWidget* widget)
{
ExampleAppWindow* win = EXAMPLE_APP_WINDOW(widget);
save_some_state(win);
GTK_WIDGET_CLASS(example_app_window_parent_class)->destroy (widget);
}
static void
example_app_window_class_init (ExampleAppWindowClass *klass)
{
GtkWidgetClass* widget_class = GTK_WIDGET_CLASS (klass);
widget_class->destroy = on_app_window_destroy;
}
Well, it definitely looks like you are destroying it twice by calling
GTK_WIDGET_CLASS(example_app_window_parent_class)->destroy (widget);
in the on_app_window_destroy callback
Where are you storing example_app_window_parent_class? Is this derived from the widget? As GtkNerd says it may duplicate things if it is not chained right.
I am not entirely confident of the internals. For Gtk2, destroy is a GtkObject signal not a GtkWidget signal so you would cast as GTK_OBJECT_CLASS in that case, though that is likely irrelevant - For Gtk3 it is fine as is. I am not sure about the internals but the destroy signal might get called multiple times due to reference counting. A safer option is to override finalize as it should only get called the once irrespective.

How to avoid Thread.sleep() in a for loop from interrupting the UI Thread?

I have the following pseudo code to clarify my problem and a solution. My original posting and detailed results are on Stack Overflow at: Wait() & Sleep() Not Working As Thought.
public class PixelArtSlideShow { // called with click of Menu item.
create List<File> of each selected pixelArtFile
for (File pixelArtFile : List<File>) {
call displayFiles(pixelArtFile);
TimeUnits.SECONDS.sleep(5); }
}
public static void displayFiles(File pixelArtFile) {
for (loop array rows)
for (loop array columns)
read-in sRGB for each pixel - Circle Object
window.setTitle(....)
}
// when above code is used to Open a pixelArtFile, it will appear instantly in a 32 x 64 array
PROBLEM: As detailed extensively on the other post. Each pixelArtFile will display the setTitle() correctly and pause for about 5 secs but the Circle’s will not change to the assigned color except for the last file, after the 5 secs have passed. It's like all the code in the TimeUnits.SECONDS.sleep(5); are skipped EXCEPT the window.setTitle(...)?
My understanding is the TimeUnits.SECONDS.sleep(5); interrupts the UI Thread uncontrollable and I guess must somehow be isolated to allow the displayFiles(File pixelArtFile) to fully execute.
Could you please show me the most straight forward way to solve this problem using the pseudo code for a more completed solution?
I have tried Runnables, Platform.runLater(), FutureTask<Void>, etc. and I'm pretty confused as to how they are meant to work and exactly coded.
I also have the two UI windows posted on the web at: Virtual Art. I think the pixelArtFile shown in the Pixel Array window may clarify the problem.
THANKS
Don't sleep the UI thread. A Timeline will probably do what you want.
List<File> files;
int curFileIdx = 0;
// prereq, files have been appropriately populated.
public void runAnimation() {
Timeline timeline = new Timeline(
new KeyFrame(Duration.seconds(5), event -> {
if (!files.isEmpty()) {
displayFile(curFileIdx);
curFileIdx = (curFileIdx + 1) % files.size();
}
})
);
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();
}
// prereq, files have been appropriately populated.
public void displayFile(int idx) {
File fileToDisplay = files.get(idx);
// do your display logic.
}
Note, in addition to the above, you probably want to run a separate task to read the file data into memory, and just have a List<ModelData> where ModelData is some class for data you have read from a file. That way you wouldn't be continuously running IO in your animation loop. For a five second per frame animation, it probably doesn't matter much. But, for a more frequent animation, such optimizations are very important.

Delay 'glitch' with dispatch_after swift

Currently, i have a delay function as follows:
//Delay function from http://stackoverflow.com/questions/24034544/dispatch-after-gcd-in-swift/24318861#24318861
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
This code works for what i need, but as soon as the delay gets greater than 13 or so seconds, it seems to glitch out and stop delaying. Does anyone know a solution to this, or even while this is happening?
Here is the code in my use:
var delayTime = Double(1)
for number in self.gameOrder{
if number == 0{
delay(delayTime++){self.greenButton.highlighted = true}
self.delay(delayTime++){
self.greenButton.highlighted = false
}
}
else if number == 1{
delay(delayTime++){self.redButton.highlighted = true}
self.delay(delayTime++){
self.redButton.highlighted = false
}
}
else if number == 2{
delay(delayTime++){self.yellowButton.highlighted = true}
self.delay(delayTime++){
self.yellowButton.highlighted = false
}
}
else if number == 3{
delay(delayTime++){self.blueButton.highlighted = true}
self.delay(delayTime++){
self.blueButton.highlighted = false
}
}
println(delayTime)
}
}
}
Once delayTime gets to 13, the delay starts to play up.
Thanks!
You didn't say what platform/OS, but if on iOS, this behavior changed from iOS 7 to iOS 8. It would appear to be coalescing the timers (a power saving feature to group similar timer events together to minimize the power consumption).
The solution is to refactor the code either to use a single repeating timer or rather than scheduling all of the dispatch_after calls up front, have each dispatch_after trigger the next dispatch_after in its completion block (thus never having a bunch of dispatch_after calls pending at the same time that it might be coalesced together).
By the way, if using a repeating timer, you might want to use a dispatch source timer rather than a NSTimer, as this not only gives you the ability to specify the desired leeway, but the third parameter of dispatch_source_set_timer lets you specify a value of DISPATCH_TIMER_STRICT which:
Specifies that the system should make a best effort to strictly observe the
leeway value specified for the timer via dispatch_source_set_timer(), even
if that value is smaller than the default leeway value that would be applied
to the timer otherwise. A minimal amount of leeway will be applied to the
timer even if this flag is specified.
CAUTION: Use of this flag may override power-saving techniques employed by
the system and cause higher power consumption, so it must be used with care
and only when absolutely necessary.
In Mac OS X, this can be used to turn off "App Nap" feature (where timers will be more significantly altered in order to maximize battery life), but given the appearance of this timer coalescing in iOS, it might be a useful option here, too.

How to pause a loop to ask for input (iPhone)

I have a fairly simple looped operation that checks for obvious errors and likely problems in a data structure. I won't go into detail about it. What I want to be able to do is pause the execution of this loop whenever an error is encountered so that I can ask the user what they want to do about that error, before continuing to check the remaining data.
Can anyone give any ideas about how best to do that?
-Ash
This will stop your loop for 0.25 seconds, but it's not what you are looking to do. You need to reformulate your question first.
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.25, false);
Don't do long operations inside a loop in the UI run loop. It presents a non-responsive UI to the user; and the OS may kill the app if it locks up for too long.
Break the loop into short callbacks (make the inside of each loop iteration a method), and exit each callback after maybe a fraction of a seconds worth of inner loop operations.
Or execute the loop as a task in a background thread, and use locks to stop the loop while waiting for messages from the foreground UI run loop about what to do for some loop state.
Seems like UIAlertView is what you are looking for:
UIAlertView Class Reference
UIAlertView is asynch, so it won't pause the loop.
There are cleverer ways to write your loop, e.g. using blocks or completion handlers, but I'd suggest the EASIEST way is simply convert your code from:
-(void) method
{
...
for( int i=0; i<10; i++)
{
check_loop_item(i);
}
}
to:
int iCurrent, iEnd;
-(void) method
{
...
iCurrent = 0;
iEnd = 10;
[self doLoop];
}
-(void) doLoop
{
if( iCurrent >= iEnd )
return;
check_loop_item(iCurrent);
...
if( error )
{
// Popup a UIAlertView
}
else
{
iCurrent++;
[self doLoop];
}
...and in the callback method from UIAlertView, do:
-(void) callbackFromUIAlertView
{
iCurrent++;
[self doLoop];
}
...i.e. a loop that runs once at a time, and lets you arbitrarily stop / pause / resume it.