2013-06-25 34 views
4

我有一個NSOperation,我把一個隊列。 NSOperation會執行一些長時間運行的照片處理,然後將信息/元數據保存在該照片的核心數據中。在我的自定義的主要方法的NSOperation類是在哪裏執行的代碼下面的框魔法記錄背景保存似乎阻止用戶界面

-(void)main 
{ 
    //CODE ABOVE HANDLES PHOTO PROCESSING... 
    //........ 

    //THEN I SAVE ALL DATA BELOW LIKE SO 
    [MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) { 

     Post *post = [Post createInContext:localContext]; 

     //set about 15 pieces of data, all strings and floats 
     post.XXXX = XXXXX; 
     post.DDDD = DDDDD; 
     etc... 
    } completion:^(BOOL success, NSError *error) { 
     NSLog(@"Done saving"); 
    }]; 
} 

我的問題是,即使只有3張照片時,它保存它真的凍結我的UI。我會認爲在NSOperation中執行此操作會很好。

我應該補充說,每個NSOperation處理一張照片,所以有時隊列可以有5-10張照片,但我不認爲這會產生任何影響,即使只有三個像我說的凍結UI。

謝謝你的幫助。

UPDATE:------------ * --------------

我切換到2.2版本,但是,這似乎是阻止用戶界面甚至更...現在我正在使用

-(void)main 
{ 
    NSManagedObjectContext *localContext = [NSManagedObjectContext contextForCurrentThread]; 
    //CODE BELOW HANDLES PHOTO PROCESSING... 
    //........ 

    //THEN I SAVE ALL DATA BELOW LIKE SO 
    Post *post = [Post createInContext:localContext]; 

    //set about 15 pieces of data, all strings and floats 
    post.XXXX = XXXXX; 
    post.DDDD = DDDDD; 


    [localContext saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) { 

    }]; 
} 

這一切都在我的NSOperation類中完成,我做錯了什麼?

+0

你如何開始操作? –

+0

你有沒有簡介確定延遲的確切位置? – Wain

+0

只要處理髮生在主線程中,你的UI就會凍結。 – mrosales

回答

10

不要把saveWithBlock在後臺線程調用。你有效地從後臺線程創建後臺線程,在這種情況下,這隻會讓你放慢速度。你應該能夠調用saveWithBlock,它應該把你所有的保存代碼放在後臺。但是,我也注意到,您在代碼的主UI頁面中進行了所有更改,並且僅在以後調用save。這是這種方法的錯誤用法。你想要做的事更是這樣的:

[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) { 
    Post *post = [Post createInContext:localContext]; 

    //photo processing 
    //update post from photo processing 
} completion:^(BOOL success, NSError *error) { 
    //This is called when data is in the store, and is called on the main thread 
}]; 

如果你確實需要一個的NSOperation,我提出一個不同的模式:

- (void) main { 
    NSManagedObjectContext *localContext = [NSManagedObjectContext confinementContext]; 
    // Do your photo stuff here 

    Post *post = [Post createInContext:localContext]; 
    //more stuff to update post object 

    [localContext saveToPersistentStoreAndWait]; 

} 
+0

感謝您的幫助,我在線程內古怪的代碼和線程放置似乎是問題。我也更新到2.2版本,這似乎也有幫助。我結束了使用你的建議saveWithBlock,NSOperation真的不需要。 – inks2002

0

請注意如何開始操作。

[operation start] 

將開始在當前線程上運行,所以如果你在主線程(這是一個UI)調用它,它會擋住接口。

你應該運行添加到隊列中,使得它在後臺運行,而無需佔用主線程

[[NSOperationQueue new] addOperation:operation]; 
+0

我開始像你上面說的那樣。 – inks2002

+0

'[操作開始]'? –

+0

對不起,我應該已經更清楚了[[NSOperationQueue new] addOperation:operation]; – inks2002