[英]Objective C to Swift - DoWithBlock
我試圖僅在目標C類函數完成時在Swift中創建一個數組。 我在目標C函數中使用了DoWithBlock,但是我對IOS並不陌生,因此我試圖弄清楚它實際上是否以正確的順序運行。
我得到了幫助,提出了解決方案,但是我不確定我對該答案所做的擴展是否正確,我認為這應該是一個新問題。
在目標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函數,希望創建這樣的數組:
override func viewDidLoad() {
super.viewDidLoad()
let scanTable = ScanTable();
scanTable.scanTableDoWithBlock { (scanResult, error) in
let swiftArray = scanTable.scanResult
}
代碼“ let swiftArray = scanTable.scanResult”是否僅在目標C函數完成時運行,或者如果它在另一個C函數之前運行就純屬幸運。 我尚未找到有關快速使用塊的良好文檔。
謝謝你的幫助
///編輯我最近一次在swift viewwilappear中調用目標C掃描函數的嘗試(在scan函數中,正在創建數組,我可以對其進行遍歷。在swift方面,我得到兩個數組都返回nill代碼正在運行和////
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")
}
}
}
viewDidLoad
調用scanTable.scanTableDoWithBlock
; 如果在MainThread上進行了大量計算,則會延遲視圖轉換。 在viewDidAppear
調用它。 let swiftArray = scanTable.scanResult
將在scanTableDoWithBlock
完成之后調用。
如果task.exception
你應該打電話
if (handler != nil) { handler(nil, nil); }
刪除return nil
因為它不會調用完成塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.