目标C到Swift – DoWithBlock

我想只在一个目标C类函数完成时在Swift中创build一个数组。 我在目标C函数中使用了一个DoWithBlock,但是我是IOS新手,正在尝试解决它是否按照正确的顺序运行。

我在这里得到了解决scheme的帮助,但是我不确定我做了什么来解决这个问题是正确的,我相信这应该是一个新问题。

在目标C类中,我用这样的块调用函数:

- (void)scanTableDoWithBlock:(void(^)(NSArray *scanResult, NSError *error))handler { AWSDynamoDBObjectMapper *dynamoDBObjectMapper = [AWSDynamoDBObjectMapper defaultDynamoDBObjectMapper]; AWSDynamoDBScanExpression *scanExpression = [AWSDynamoDBScanExpression new]; scanExpression.limit = @10; [[dynamoDBObjectMapper scan:[Mapper class] expression:scanExpression] 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; }]; } @end 

然后在Swift类中,我调用目标C函数,我希望创build这样的数组:

 override func viewDidLoad() { super.viewDidLoad() let scanTable = ScanTable(); scanTable.scanTableDoWithBlock { (scanResult, error) in let swiftArray = scanTable.scanResult } 

代码“let swiftArray = scanTable.scanResult”仅在目标C函数完成时才运行,或者如果它运行在另一个之上,它将只是纯粹的运气。 我一直无法find有关在swift中使用块的好文档。

谢谢你的帮助

///编辑我最近尝试在swift中调用目标C扫描函数viewwilappear(在扫描函数中,数组正在创build,我可以循环通过它很好。在快速的一边,我得到两个数组返回为代码正在运行和////

 class RateSongsViewController: UIViewController { override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let scanTable = ScanTable(); scanTable.scanTableDoWithBlock { (scanResult, error) in let swiftArray = scanTable.scanResult if (scanTable.scanResult == nil){ print(" scanResult ARRAY IS NILL") } else { print(" scanResult ARRAY IS NOT NILL") } if (swiftArray == nil){ print(" SWIFT ARRAY IS NILL") } else { print(" SWIFT ARRAY IS NOT NILL") } } } 

  1. 不要在viewDidLoad调用scanTable.scanTableDoWithBlock ; 如果它在MainThread上的繁重计算将会延迟视图转换。 在viewDidAppear调用它。
  2. let swiftArray = scanTable.scanResultscanTableDoWithBlock完成后调用。

  3. 如果task.exception你应该打电话

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

删除return nil因为它不会调用完成块。