目标C:替换同步请求

时间:2018-09-18 21:28:45

标签: objective-c nsurlconnection objective-c-blocks nsurlsession

我在替换此代码时遇到问题。

-(NSMutableArray *) GetPrices: {

    NSError *error;
    NSURLResponse *response;
    NSData *tw_result = [NSURLConnection       
       sendSynchronousRequest:urlRequest 
       returningResponse:&response error:&error];

我的问题是调用此代码的函数处理url,然后将数据返回给调用它的方法。

以前我是这样使用的。

ViewController调用一个函数以通过创建操作队列来收集数据(以便UI和主线程可用)

     NSOperationQueue *myQueue = [NSOperationQueue new];
      NSInvocationOperation *operation = [[NSInvocationOperation alloc]
 initWithTarget:self selector:@selector(loadDataWithOperation) object:nil];
                [myQueue addOperation:operation];
                [operation release];
                [myQueue release];

操作队列中的函数调用方法以获取对象上的数据,然后该方法运行同步URLrequest。

-(void)loadDataWithOperation {

    self.sectionPriceArray = [self.myObject GetPrices];

因此myObject将返回一个价格数组。

我曾尝试使用NSSession,但由于方法在从完成处理程序获取tw_result之前终止,因此我无法弄清楚如何将结果传递回去。

任何想法我都必须在目标C中执行此操作,因为我没有客户的许可才能转换为swift。

问题的编辑,具有更多详细信息:

在我尝试过的GetPrices方法中

NSURLSession *session = [NSURLSession sharedSession];
        [[session dataTaskWithRequest:urlRequest
                    completionHandler:^(NSData *tw_result,
                                        NSURLResponse *response,
                                        NSError *error) {
                        result = [[NSString alloc] initWithData:tw_result encoding:NSUTF8StringEncoding];

        NSArray *resultArray = [result componentsSeparatedByString:@"\n"];
        }) resume];

但是我无法弄清楚如何在呼叫级别上使这项工作更上一层楼。

1 个答案:

答案 0 :(得分:1)

正如@maddy所提到的,您将要为getPrices方法使用一个完成块而不是返回值-返回值+异步不要混合。

这是将getPrices方法转换为以下内容的常规形式:

- (void)_getPricesWithCompletion:(void(^)(NSMutableArray *sectionPriceArray))priceCompletion;

此站点:http://goshdarnblocksyntax.com具有一些常见的块语法声明用法。

通常,您将调用此async方法,然后在完成块中设置iVar,并在收到新数据后重新加载关联的UI元素。遵循以下原则:

[self _getPricesWithCompletion:^(NSMutableArray *sectionPriceArray) {
    self.sectionPriceArray = sectionPriceArray;
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        // reload any UI elements dependent on your sectionPriceArray here
    }];
}];

现在在显示的示例代码中,似乎您正在使用NSOperationQueue将不同的操作排队。这里的事情可能会变得更加复杂。随后的队列操作将不等待异步操作完成再执行。因此,例如,如果您在getPrices操作之后进行了一项操作,该操作利用了获取价格的结果,那么iVar几乎肯定会在那时不包含正确的数据。在这种情况下,您需要使用某种信号量来等待异步操作完成,然后再继续执行依赖于它的操作。

这是我的意思的示例:

NotProperlyWaiting.h

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface NotProperlyWaiting : NSObject
@property (strong, nullable) NSMutableArray *sectionPriceArray;
- (void)callOperations;
- (void)fakeServerCallWithCompletion:(void(^)(NSData *tw_result, NSURLResponse *response, NSError *error))completion;
@end

NotProperlyWaiting.m

#import "NotProperlyWaiting.h"

@interface NotProperlyWaiting()
- (void)_getPricesWithCompletion:(void(^)(NSMutableArray *sectionPriceArray))priceCompletion;
- (void)_printPricesArray;
@end

@implementation NotProperlyWaiting

- (instancetype)init {
    self = [super init];
    if (self) {
        _sectionPriceArray = [NSMutableArray array];
    }
    return self;
}

- (void)callOperations {
    // setup our completion block to be passed in (this is what will eventually set the self.sectionPricesArray
    void (^pricesCompletion)(NSMutableArray *) = ^ void (NSMutableArray *sectionPricesArrayFromCompletion){
        self.sectionPriceArray = sectionPricesArrayFromCompletion;
    };
    NSOperationQueue *myQueue = [NSOperationQueue new];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(_getPricesWithCompletion:) object:pricesCompletion];
    NSInvocationOperation *printOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(_printPricesArray) object:nil];
    [myQueue addOperation:operation];
    [myQueue addOperation:printOperation];
}

- (void)_getPricesWithCompletion:(void(^)(NSMutableArray *sectionPricesArray))priceCompletion {
    [self fakeServerCallWithCompletion:^(NSData *tw_result, NSURLResponse *response, NSError *error) {
        // check the error or response or whatever else to verify that the data is legit from your server endpoint here
        // then convert the data to your mutable array and pass it through to our completion block
        NSString *stringData = [[NSString alloc] initWithData:tw_result encoding:NSUTF8StringEncoding];
        NSMutableArray *tempPricesArray = [NSMutableArray arrayWithArray:[stringData componentsSeparatedByString:@"\n"]];
        // now our completion block passing in the result prices array
        priceCompletion(tempPricesArray);
    }];
}

- (void)_printPricesArray {
    NSLog(@"NotWaiting -- Prices array : %@", self.sectionPriceArray);
}

// this is a fake version of NSURLSession
- (void)fakeServerCallWithCompletion:(void(^)(NSData *tw_result, NSURLResponse *response, NSError *error))completion {
    NSString *fakeServerResponse = @"FirstThing\nSecondThing\nThirdThing";
    NSData *fakeData = [fakeServerResponse dataUsingEncoding:NSUTF8StringEncoding];
    NSURLResponse *fakeResponse = [[NSURLResponse alloc] init];
    NSError *fakeError = [NSError errorWithDomain:@"FakeErrorDomain" code:33 userInfo:nil];
    // never call sleep in your own code, this is just to simulate the wait time for the server to return data
    sleep(3);
    completion(fakeData,fakeResponse,fakeError);
}

    NS_ASSUME_NONNULL_END

ProperlyWaiting.h(NotProperlyWaiting.h的子类,以重新使用callOperation和fakeServerCallWithCompletion:)

#import "NotProperlyWaiting.h"

NS_ASSUME_NONNULL_BEGIN

@interface ProperlyWaiting : NotProperlyWaiting

@end

NS_ASSUME_NONNULL_END

ProperlyWaiting.m

#import "ProperlyWaiting.h"

@interface ProperlyWaiting()
- (void)_getPricesWithCompletion:(void(^)(NSMutableArray *sectionPricesArray))priceCompletion;
- (void)_printPricesArray;
@property dispatch_semaphore_t semaphore;
@end

@implementation ProperlyWaiting

- (void)callOperations {
    self.semaphore = dispatch_semaphore_create(0);
    [super callOperations];
}

// identical implementations to NotProperlyWaiting, but this time we'll use a semaphore to ensure the _printPricesArray waits for the async operation to complete before continuing
- (void)_getPricesWithCompletion:(void(^)(NSMutableArray *sectionPricesArray))priceCompletion {
    [self fakeServerCallWithCompletion:^(NSData *tw_result, NSURLResponse *response, NSError *error) {
        // check the error or response or whatever else to verify that the data is legit from your server endpoint here
        // then convert the data to your mutable array and pass it through to our completion block
        NSString *stringData = [[NSString alloc] initWithData:tw_result encoding:NSUTF8StringEncoding];
        NSMutableArray *tempPricesArray = [NSMutableArray arrayWithArray:[stringData componentsSeparatedByString:@"\n"]];
        // now our completion block passing in the result prices array
        priceCompletion(tempPricesArray);
        // signal our semaphore to let it know we're done
        dispatch_semaphore_signal(self.semaphore);
    }];
}

- (void)_printPricesArray {
    // wait for the semaphore signal before continuing (so we know the async operation we're waiting on has completed)
    dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
    NSLog(@"Waiting -- Prices array : %@", self.sectionPriceArray);
}

@end

使用此类的示例调用:

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NotProperlyWaiting *notWaiting = [[NotProperlyWaiting alloc] init];
    [notWaiting callOperations];

    ProperlyWaiting *waiting = [[ProperlyWaiting alloc] init];
    [waiting callOperations];
}

日志中的输出为:

NotWaiting -- Prices array : (
) 

然后3秒后:

Waiting -- Prices array : (
    FirstThing,
    SecondThing,
    ThirdThing
)

与该主题相关的有用文档的一些其他链接:

https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html

https://developer.apple.com/documentation/dispatch/1452955-dispatch_semaphore_create