2012-11-16 77 views
1

我正在開發一個郵件客戶端使用MailCore框架(基於C庫LibEtPan)。我想處理服務器連接和新線程或隊列中的所有請求,並將信息推送到主隊列以進行UI更新。MailCore併發支持

MailCore變量似乎無法在線程之間共享的問題。

@implementation Controller 
{ 
    NSOperationQueue *_queue; 
    CTCoreAccount *_account; 
    CTCoreFolder *_inbox; 
    NSArray *_messages; 
} 

- (id)init 
{ 
    // stuff 

    _queue = [[NSOperationQueue alloc] init]; 

    [_queue addOperationWithBlock:^ 
    { 
     _account = [[CTCoreAccount alloc] init]; 

     BOOL success = [_account connectToServer:@"imap.mail.com" port:993 connectionType:CTConnectionTypeTLS authType:CTImapAuthTypePlain login:@"[email protected]" password:@"Password"]; 

     if (success) 
     { 
      CTCoreFolder *inbox = [_account folderWithPath:@"INBOX"]; 
      NSArray *messages = [inbox messagesFromSequenceNumber:1 to:0 withFetchAttributes:CTFetchAttrEnvelope]; 

      [[NSOperationQueue mainQueue] addOperationWithBlock:^ 
       { 
        _messages = [messages copy]; 
        // UI updates here 
       }]; 
     } 
    }]; 

    // Other stuff 
} 

後來,例如這個方法可稱爲:

- (void)foo 
{ 
    [_queue addOperationWithBlock:^ 
    { 
     CTCoreMessage *message = [_messages objectAtIndex:index]; 

     BOOL isHTML; 
     NSString *body = [message bodyPreferringPlainText:&isHTML]; 

     [[NSOperationQueue mainQueue] addOperationWithBlock:^ 
      { 
       // UI Updates 
      }]; 
    }]; 
} 

這裏,body是空的,因爲CTCore變量無法從_queue執行新的請求。

根據這comment,每個線程需要是自己的CTCoreAccount,等等...... iOS上的線程應該有共享內存。我不明白爲什麼在線程中重複使用相同的CTCoreAccount不起作用,即使LibetPan庫中使用了引用。 如何定義一個唯一的CTCoreAccount或CTCoreFolder「附加」到可以多次重用的不同線程或隊列?

任何意見,將不勝感激。謝謝。

+0

該關鍵字是線程遏制哪些coredata和地址簿也採用 –

+0

感謝您的信息。我會檢查的。 – aaaaahaaaaa

+0

無法處理比CoreData上下文管理更多的Thread Containment。我在這裏沒有使用CoreData。基本上,我想要的是在同一個NSOperationQueue的不同NSOperation之間共享同一個對象。 – aaaaahaaaaa

回答

1

答案由MRonge here給出。

的一種方式是創建一個包含兩個NSOperationQueue 一個對象(與maxConcurrentOperationCount = 1)和CTCoreAccount。所有 工作爲該帳戶通過該對象,並且只在一個線程上一次執行 。然後,您可以爲要訪問的每個 帳戶設置這些對象中的一個。