Store a closure as a variable in Swift

The compiler complains on var completionHandler: (Float)->Void = {} because the right-hand side is not a closure of the appropriate signature, i.e. a closure taking a float argument. The following would assign a “do nothing” closure to the completion handler: var completionHandler: (Float)->Void = { (arg: Float) -> Void in } and this can be … Read more

Waiting until two async blocks are executed before starting another block

Use dispatch groups: see here for an example, “Waiting on Groups of Queued Tasks” in the “Dispatch Queues” chapter of Apple’s iOS Developer Library’s Concurrency Programming Guide Your example could look something like this: dispatch_group_t group = dispatch_group_create(); dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ { // block1 NSLog(@”Block1″); [NSThread sleepForTimeInterval:5.0]; NSLog(@”Block1 End”); }); dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ { // … Read more

How do I avoid capturing self in blocks when implementing an API?

Short answer Instead of accessing self directly, you should access it indirectly, from a reference that will not be retained. If you’re not using Automatic Reference Counting (ARC), you can do this: __block MyDataProcessor *dp = self; self.progressBlock = ^(CGFloat percentComplete) { [dp.delegate myAPI:dp isProcessingWithProgress:percentComplete]; } The __block keyword marks variables that can be modified … Read more

Block Declaration Syntax List

List of Block Declaration Syntaxes Throughout, let return_type be the type of object/primitive/etc. you’d like to return (commonly void) blockName be the variable name of the block you’re creating var_type be the type object/primitive/etc. you’d like to pass as an argument (leave blank for no parameters) varName be the variable name of the given parameter … Read more

How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

I think you’re looking for dispatch_after(). It requires your block to accept no parameters, but you can just let the block capture those variables from your local scope instead. int parameter1 = 12; float parameter2 = 144.1; // Delay execution of my block for 10 seconds. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ NSLog(@”parameter1: %d parameter2: … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)