Is the weakSelf/strongSelf dance really necessary when referencing self inside a non-retained completion called from a UIViewController?

As I believe you correctly diagnosed, using self will not necessarily cause strong reference cycle in this scenario. But this will retain the view controller while the network operation completes, and in this case (as in most cases), there’s no need to. Thus, it may not be necessary to do use weakSelf, but probably prudent … Read more

iOS blocks and strong/weak references to self

You don’t need to make two sets of weak references. What you want to avoid with blocks is a retain cycle—two objects keeping each other alive unnecessarily. If I have an object with this property: @property (strong) void(^completionBlock)(void); and I have this method: – (void)doSomething { self.completionBlock = ^{ [self cleanUp]; }; [self doLongRunningTask]; } … Read more

Block references as instance vars in Objective-C

Sure. typedef void(^MyCustomBlockType)(void); @interface MyCustomObject { MyCustomBlockType block; } @property (nonatomic, copy) MyCustomBlockType block; //note: this has to be copy, not retain – (void) executeBlock; @end @implementation MyCustomObject @synthesize block; – (void) executeBlock { if (block != nil) { block(); } } – (void) dealloc { [block release]; [super dealloc]; } @end //elsewhere: MyCustomObject * … Read more

Can AFNetworking return data synchronously (inside a block)?

To block the execution of the main thread until the operation completes, you could do [operation waitUntilFinished] after it’s added to the operation queue. In this case, you wouldn’t need the return in the block; setting the __block variable would be enough. That said, I’d strongly discourage forcing asynchronous operations to synchronous methods. It’s tricky … Read more

Difference between block (Objective-C) and closure (Swift) in iOS

Excerpt From: Apple Inc. “Using Swift with Cocoa and Objective-C.” iBooks: “Swift closures and Objective-C blocks are compatible, so you can pass Swift closures to Objective-C methods that expect blocks. Swift closures and functions have the same type, so you can even pass the name of a Swift function. Closures have similar capture semantics as … Read more

Unable to access global variables in dispatch_async : “Variable is not Assignable (missing _block type specifier)” [duplicate]

You must use the __block specifier when you modify a variable inside a block, so the code you gave should look like this instead: __block NSString *textString; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, (unsigned long)NULL), ^(void) { textString = [self getTextString]; }); Blocks capture the state of the variables referenced inside their bodies, so the captured variable must be declared … Read more

tech