简体   繁体   中英

Synchronous connecting to AWS DynamoDB in Objective-c

How can I implement synchronous access to AWS DynamoDB in Objective-c?

I understood asynchronous access to DynamoDB using Bolts BFTask as below but I need "synchronous" connecting.

----added some information----

I called "ddbIDQuery" method in "DynamoQuery" class but it returned (null), because of the Bolts asynchronous transaction?? What is the best way to get the result?

// 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 has a method called - waitUntilFinished to make it a synchronous method; however, you should avoid it if possible. See Make it synchronous section of our blog for more details.

In most cases you do not need synchronous access. You just do not understand the complexity of asynchronous code execution. But of course I do not know, if this applies to your case.

However, you can use semaphores for this purpose, if the asynchronous code is executed on a different thread. (And not only "pseudo-asynchronous" via run loop dispatch.)

// 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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