Nicholas Muir Nicholas Muir - 1 year ago 140
Swift Question

Objective C to Swift - DoWithBlock

I am trying to only create an array in Swift when an objective C class function is completed. I am using a DoWithBlock in the objective C function but I am am new to IOS and am trying to work out if it is actually running in the correct order.

I got help to come up the solution on here but I am not sure if what I did to extend on that answer is correct and I believe it should be a new question.

In the objective C class I am calling the function with the block like this:

- (void)scanTableDoWithBlock:(void(^)(NSArray *scanResult, NSError *error))handler {

AWSDynamoDBObjectMapper *dynamoDBObjectMapper = [AWSDynamoDBObjectMapper defaultDynamoDBObjectMapper];
AWSDynamoDBScanExpression *scanExpression = [AWSDynamoDBScanExpression new];
scanExpression.limit = @10;

[[dynamoDBObjectMapper scan:[Mapper class]
continueWithBlock:^id(AWSTask *task) {
if (task.error) {
NSLog(@"The request failed. Error: [%@]", task.error);
if (handler != nil) {
handler(nil, task.error);
if (task.exception) {
NSLog(@"The request failed. Exception: [%@]", task.exception);
if (task.result) {
AWSDynamoDBPaginatedOutput *paginatedOutput = task.result;
NSMutableArray *scanResult = [[NSMutableArray alloc] initWithArray:paginatedOutput.items]; //// ADDED /////

if (handler != nil) {
handler([scanResult copy], nil);

return nil;

Then in the swift class I am calling the objective C function and I am hoping creating the array like this:

override func viewDidLoad() {

let scanTable = ScanTable();

scanTable.scanTableDoWithBlock { (scanResult, error) in

let swiftArray = scanTable.scanResult

Does the code "let swiftArray = scanTable.scanResult" only run when the objective C function has completed or would it be just pure luck if it ran before the other. I haven't been able to find good documentation on using blocks in swift.

Thanks for your help

Answer Source
  1. Don't call scanTable.scanTableDoWithBlock in viewDidLoad; if its heavy computation on MainThread it will delay the view transition. Call it in viewDidAppear.
  2. let swiftArray = scanTable.scanResult will call after scanTableDoWithBlock completion.

  3. If task.exception you should call

    if (handler != nil) {
        handler(nil, nil);

Remove return nil because it will not call completion block.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download