繁体   English   中英

在Objective-c中同步连接到AWS DynamoDB

[英]Synchronous connecting to AWS DynamoDB in Objective-c

如何在Objective-c中实现对AWS DynamoDB的同步访问?

我了解了以下使用Bolts BFTask对DynamoDB的异步访问,但是我需要“同步”连接。

----增加了一些信息----

我在“ DynamoQuery”类中调用了“ ddbIDQuery”方法,但由于Bolts异步事务而返回了(空)? 获得结果的最佳方法是什么?

// MainViewController.m

#import "DynamoQuery.h"

-(IBAction)ddqButton:(UIButton *)sender
{
    // call DynamoQuery
    DynamoQuery *dynamoQuery = [[DynamoQuery alloc] init];
    NSLog(@"dynamoQuery: %@", [dynamoQuery ddbIDQuery:@"448898329-6BC0FA0A954913043A3281599A444E3C"]);
}


// DynamoQuery.m

- (NSString *) ddbIDQuery: (NSString*)ddbID
{
    __block NSString *strpid = nil;

    AWSDynamoDBObjectMapper *dynamoDBObjectMapper = [AWSDynamoDBObjectMapper defaultDynamoDBObjectMapper];
    [[dynamoDBObjectMapper load:[PIDTable class] hashKey:ddbID rangeKey:nil] continueWithBlock:^id(AWSTask *task)
     {
         NSLog(@"ddbID: %@", ddbID);
         if (task.error){
             NSLog(@"The 1st request failed. Error: [%@]", task.error);
         }
         if (task.exception) {
             NSLog(@"The 1st request failed. Exception: [%@]", task.exception);
         }
         if (task.result) {
             PIDTable *ddbpid = task.result;
             NSData *datapid = [ddbpid.text dataUsingEncoding:NSUTF8StringEncoding];
             strpid = [[NSString alloc] initWithData:datapid encoding:NSUTF8StringEncoding];
         };
         return nil;
     }
     ];
     return strpid;
}

BFTask有一个名为方法- waitUntilFinished使其同步方法; 但是,如果可能,应避免使用它。 有关更多详细信息,请参见博客的 “使其同步”部分。

在大多数情况下,您不需要同步访问。 您只是不了解异步代码执行的复杂性。 但是我当然不知道这是否适用于您的情况。

但是,如果异步代码是在其他线程上执行的,则可以为此目的使用信号量。 (并且不仅通过运行循环调度实现“伪异步”。)

// Create a semaphore
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); // No concurrency at all

[[dynamoDBObjectMapper load:[PIDTable class] hashKey:ddbid rangeKey:nil] continueWithBlock:^id(AWSTask *task)
{
     …
     // Signal that work is done
    dispatch_semaphore_signal(semaphore); // done

    return nil;
}
];

// Wait for signal
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); // Probably you do not want to wait for ever.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM