相关疑难解决方法(0)

Block_release在后台线程上释放UI对象

WWDC 2010"Blocks and Grand Central Dispatch"演讲中提出的模式之一是使用嵌套的dispatch_async调用在后台线程上执行耗时的任务,然后在任务完成后更新主线程上的UI

dispatch_async(backgroundQueue, ^{
    // do something time consuming in background
    NSArray *results = ComputeBigKnarlyThingThatWouldBlockForAWhile();

    // use results on the main thread
    dispatch_async(dispatch_get_main_queue(), ^{
        [myViewController UpdateUiWithResults:results];
    });
});
Run Code Online (Sandbox Code Playgroud)

由于"myViewController"正在块中使用,它会自动获得"保留",并在清除块时稍后获得"释放".

如果块的'release'调用是最终的释放调用(例如,用户在后台任务运行时导航远离视图),则调用myViewController dealloc方法 - 但是它在后台线程上调用!!

UIKit对象不喜欢在主线程之外取消分配.在我的例子中,UIWebView抛出异常.

这个WWDC如何呈现模式 - 特别提到避免UI锁定的最佳新方法 - 是如此有缺陷?我错过了什么吗?

grand-central-dispatch ios objective-c-blocks

17
推荐指数
1
解决办法
4217
查看次数

多线程ViewController中的UIWebView

我在viewcontroller中有一个UIWebView,它有两个方法如下.问题是如果我在第二个线程完成之前弹出(点击导航栏)此控制器,应用程序将在[super dealloc]之后崩溃,因为"试图从主线程以外的线程获取Web锁定或这可能是从辅助线程调用UIKit的结果." 任何帮助将非常感激.

-(void)viewDidAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(load) object:nil];
    [operationQueue addOperation:operation];
    [operation release];
}

-(void)load {
    [NSThread sleepForTimeInterval:5];
    [self performSelectorOnMainThread:@selector(done) withObject:nil waitUntilDone:NO];
}
Run Code Online (Sandbox Code Playgroud)

iphone cocoa-touch memory-management objective-c uikit

9
推荐指数
2
解决办法
1万
查看次数

NSNotificationCenter removeObserver:在dealloc和线程安全中

我正在使用ARC,我正在[[NSNotificationCenter defaultCenter] removeObserver:someObserver];观察者的呼唤dealloc.

来自NSNotificationCenter类参考

确保在notificationObserver或addObserver中指定的任何对象之前调用此方法(或removeObserver:name:object :):selector:name:is is deallocated.

NSNotificationCenter不保留观察者.

Q1:NSNotificationCenter线程安全吗?

在这种情况下,观察者正被解除分配(并从观察中心移除观察者),另一个线程同时发布通知.

我遇到随机崩溃,我怀疑是这种情况.

Q2:这种情况可能吗?

Q3:它会导致EXC_BAD_ACCESS吗?

Q4:那么,[[NSNotificationCenter defaultCenter] removeObserver:someObserver];观察者的呼叫是否安全dealloc

Q5:如果不安全,我应该在哪里打电话removeObserver:

memory-management objective-c nsnotificationcenter automatic-ref-counting

6
推荐指数
2
解决办法
6206
查看次数