2010-12-09 115 views
0

親愛的社區。 當我有我的應用程序的穩定版本,而我不開始更改代碼到多線程版本。是什麼以前的版本之間的區別:(無效)的applicationDidFinishLaunching :(NSNotification *)aNotification 我做循環來添加到隊列我的代碼:核心數據多線程使用

NSOperationQueue *opQueueImportUpdateFirstTimeData = [[[NSOperationQueue alloc]init]autorelease]; 
int i = 0; 
for (NSString *carrier in currentCarriers) 
{ 
    AppController *operation = [[AppController alloc] initAndUpdateCarrier:carrier identifier:i]; 
    [opQueueImportUpdateFirstTimeData addOperation:operation]; 
    i++; 
} 

外部類有:

- (id)initAndUpdateCarrier:(NSString *)forCarrier 
       identifier:(NSUInteger)iQuene; 
{ 
    [super init]; 
    [self setIdentifierQuene:iQuene]; 
    [self setStartForCarrier:forCarrier]; 
    [self setPercentDone:0.0]; 

這一點是非常重要的:

[self setDatabase:[[MySQLIXC alloc] init]]; 

你不能分配其他類我ü正處理多線程,我不知道爲什麼,但是這是需要malloc_error在整個隊列

[self setAppDelegate:[[NSApplication sharedApplication] delegate]]; 
    [self setManagedObjectContext:[[NSManagedObjectContext alloc] init]]; 
    return self; 
} 

而在外部類我有:

-(void) main; 
{ 

[self makeUpdatesForCarrier:startForCarrier andTypeOfOperation:@"rates" forDirection:@"incoming"];// mySqlConnector:database]; 

這是一個只是其工作的一些功能當地moc。 當我啓動應用程序時,界面沒有放置在後臺,只有在所有隊列都完成後纔開始可視化。

在我嘗試在我的外部類中嘗試alloc] init] MySQLIXC類,但它給了我很多malloc_error_break異常,就像有人試圖爲我凍結內存一樣。 Tnx。

這裏是MOC聲明: 中.H:

@property(retain) NSManagedObjectContext *managedObjectContext; 

在的.m: @synthesize managedObjectContext;

設置持久存儲區協調員:

[[self managedObjectContext] setUndoManager:nil]; 
[[self managedObjectContext] setPersistentStoreCoordinator:[appDelegate persistentStoreCoordinator]]; 

合併變化與主要商務部:

- (void)mergeChanges:(NSNotification *)notification; 
{ 
AppDelegate *appDelegate = [[NSApplication sharedApplication] delegate]; 
NSManagedObjectContext *mainContext = [appDelegate managedObjectContext]; 

// Merge changes into the main context on the main thread 
[mainContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) 
           withObject:notification 
          waitUntilDone:YES]; 

而且在一個地方我的代碼我使用的一個主要MOC(僅適用於讀取信息,我知道moc不是線程安全的):

AppDelegate *appDelegate = [[NSApplication sharedApplication] delegate]; 
NSManagedObjectContext *mainContext = [appDelegate managedObjectContext]; 

NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease]; 
[request setEntity:[NSEntityDescription entityForName:@"DestinationsListForSale" 
           inManagedObjectContext:mainContext]]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"lastUsedProfit > 0"]; 
[request setPredicate:predicate]; 

回答

1

首先,CoreData不是線程安全的。我強烈建議,如果你不能很好地理解核心數據,那麼你就保持應用程序是單線程的,或者至少確保你總是從一個線程訪問商店(可能最好使用主線程)。

這就是說,這不會導致malloc_error_breaks AFAIK。你會看到核心數據合併錯誤異常和類似的問題。

你能證明你設置了商務部進一步的代碼 - 只是分配和INITING一個MOC是不夠的 - 你必須設置它的NSPersistentStoreCoordinator

+0

親愛的羅傑,問題是更新。主要問題,我發現,我不能在代碼中創建外部類的實例,只是在init中。我做了更改後,所有的malloc錯誤都沒有了。但是在這種情況下,你可能會提出更多的建議,例如我可以如何在線程之間保存一些數據,比如數組。 – Alex 2010-12-09 15:52:25