Ios NSString在时间之前重新分配

Ios NSString在时间之前重新分配,ios,objective-c,swift,iphone,xcode,Ios,Objective C,Swift,Iphone,Xcode,我在我的应用程序中使用WKWebView通过javascript从HTML获取数据,我使用以下代码: NSString *jsCall = [NSString stringWithFormat:@"xxxxxx('%@');",html]; __block NSString *searchJson = nil; dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); dispatch_sync(dispatch_get_m

我在我的应用程序中使用
WKWebView
通过javascript从HTML获取数据,我使用以下代码:

NSString *jsCall = [NSString stringWithFormat:@"xxxxxx('%@');",html];

__block NSString *searchJson = nil;

dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_sync(dispatch_get_main_queue(), ^{
    [self.searchWebView evaluateJavaScript:jsCall completionHandler:^(id result, NSError * _Nullable error) {
        if (error || result == nil || ![result isKindOfClass:[NSString class]]) {
            searchJson = nil;
        } else {
            searchJson = result;
        }

        dispatch_semaphore_signal(semaphore);
    }];
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

if ([NSString stringIsNilOrEmpty:searchJson]) {
    return nil;
}

return [self getResultsWithJSonString:searchJson];
我需要等待响应,因此我正在使用
信号量\u wait
方法,它工作正常,但有时
searchJson
会从内存中释放出来,并且在
[NSString stringIsNilOrEmpty:searchJson]
中,我遇到以下错误:

EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000443439e70

你知道如何解决这个问题吗?我在项目中使用非ARC。

如果它是非ARC,则必须显式保留结果(因为回调可能位于不同的线程中),如

然后,为了避免泄漏,使用

dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
[searchJson autorelease]; // << call it here, once !!

if ([NSString stringIsNilOrEmpty:searchJson]) {
    return nil;
}

return [self getResultsWithJSonString:searchJson];
dispatch\u semaphore\u wait(信号量,dispatch\u TIME\u永远);

[searchJson自动释放];//可能尝试
dispatch\u semaphore\u wait(semaphore,dispatch\u TIME\u ever)
就在
dispatch\u sync
的底部,或者使用
dispatch\u async
我也在另一种方法中使用
searchJson
,所以当我使用完它后,我应该调用
[searchJson autorelease]
?@MTA,你在另一种方法中的意思是什么?规则是保持retain/autorelease对,如图所示;如果你调用第二个自动释放,你将在自动释放池的末尾崩溃。如果您显示代码会更好。
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
[searchJson autorelease]; // << call it here, once !!

if ([NSString stringIsNilOrEmpty:searchJson]) {
    return nil;
}

return [self getResultsWithJSonString:searchJson];