3

我将一个块传递给稍后执行此块的异步方法。如果我在将块传递给 someMethod:success:failure 之前不复制块,我的应用程序将崩溃:

有没有办法在 forwardInvocation: 中复制块,而不是在将其传递给 someMethod:success:failure: 之前复制它?

流程是someMethod:success:failure: -> forwardInvocation: -> httpGet:success:failure

httpGet:success:failure:根据 HTTP 状态码执行成功或失败块。

// AppDelegate.h

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) id response;
@property (strong, nonatomic) NSError *error;

@end

// AppDelegate.m

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // The app crashes if the blocks are not copied here!
    [[MyController new] someMethod:[^(NSString *response) {
        self.response = response;
        NSLog(@"response = %@", response);
    } copy] failure:[^(NSError *error) {
        self.error = error;
    } copy]];

    return YES;
}

@end

// MyController.h

@protocol MyControllerProtocol <NSObject>

@optional


- (void)someMethod:(void (^)(NSString *response))success
           failure:(void (^)(NSError *error))failure;

@end

@interface MyController : NSObject <MyControllerProtocol>

@end

// MyController.m

#import "MyController.h"
#import "HTTPClient.h"

@implementation MyController

- (void)forwardInvocation:(NSInvocation *)invocation {
    [invocation retainArguments];

    NSUInteger numberOfArguments = [[invocation methodSignature] numberOfArguments];

    typedef void(^SuccessBlock)(id object);
    typedef void(^FailureBlock)(NSError *error);

    __unsafe_unretained SuccessBlock successBlock1;
    __unsafe_unretained SuccessBlock failureBlock1;
    [invocation getArgument:&successBlock1 atIndex:(numberOfArguments - 2)]; // success block is always the second to last argument (penultimate)
    SuccessBlock successBlock = [successBlock1 copy];
    [invocation getArgument:&failureBlock1 atIndex:(numberOfArguments - 1)]; // failure block is always the last argument
    FailureBlock failureBlock = [failureBlock1 copy];

    NSLog(@"successBlock copy = %@", successBlock);
    NSLog(@"failureBlock copy = %@", failureBlock);

    // Simulates a HTTP request and calls the success block later!
    [HTTPClient httpGet:@"somerequest" success:successBlock failure:failureBlock];
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
    NSMethodSignature *methodSignature = [super methodSignatureForSelector:sel];
    return methodSignature;
}

@end


// HTTPClient.h

@interface HTTPClient : NSObject

+ (void)httpGet:(NSString *)path
        success:(void (^)(id object))success
        failure:(void (^)(NSError *error))failure;

@end

// HTTPClient.m

#import "HTTPClient.h"

@implementation HTTPClient

+ (void)httpGet:(NSString *)path
        success:(void (^)(id object))success
        failure:(void (^)(NSError *error))failure
{
    // Invoke the method.
    double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(),
               ^{
                   success(@"foo");
               });
}

@end

完整的源代码可以在这里找到:https ://github.com/priteshshah1983/BlocksWithNSInvocation

你能帮忙吗?

4

1 回答 1

3

罪魁祸首是线路[invocation retainArguments]。如果你注释掉那行,它工作正常。(无论如何,这行从来都不是必需的,因为调用永远不会被异步存储或使用。)

解释:

想想做什么-retainArguments。它调用retain对象指针类型的所有参数。然后当调用被释放时,它会调用release它们。

但参数是堆栈(非复制)块。retain并且release对它没有影响(因为它不是堆对象)。因此,当它被保留时,什么也没有发生,然后(从崩溃中)调用似乎在某个时候被自动释放(这是一件非常正常的事情),因此调用的最终释放和释放是异步发生的。当调用被释放时,它会尝试释放其保留的参数,但到那时它会尝试向不再有效的堆栈块发送消息,从而导致崩溃。

PS复制块forwardInvocation:也是不必要的

于 2013-07-13T02:06:56.883 回答