Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios core data how to implement the sql transaction function?

like title. I use core data to insert item, i insert 100 items , it`s too slow. How to up the insert speed? Core Data whicher has transaction funcation?

like image 216
Leonardo zhang Avatar asked Mar 16 '12 07:03

Leonardo zhang


2 Answers

[[<#NSManagedObjectContext#> undoManager] beginUndoGrouping];
... do some data modifications ....
[[<#NSManagedObjectContext#> undoManager] endUndoGrouping];

[[<#NSManagedObjectContext#> undoManager] undo]; // rollback
...
like image 162
Hangya Avatar answered Sep 24 '22 04:09

Hangya


What you are looking for is to save in Core Data after all 100 objects have been inserted as opposed to after each insert.

When objects are inserted into Core Data they are only present in memory. To persist your new objects to disc you should save which will take all changes (inserts, updates and deletes) and write them to disc together.


If you look at the documentation for -insertObject (below) you can read that inserting an object only registers the object for being inserted when changes are saved.

insertObject:

Registers an object to be inserted in the receiver’s persistent store the next time changes are saved.

- (void)insertObject:(NSManagedObject *)object

Parameters

object

A managed object.

By further looking at the documentation for -save: (below) you will se that it will (attempt to) save all the unsaved changed, in your case all 100 inserted items.

save:

Attempts to commit unsaved changes to registered objects to their persistent store.

- (BOOL)save:(NSError **)error

Parameters

error

A pointer to an NSError object. You do not need to create an NSError object. The save operation aborts after the first failure if you pass NULL.

Return Value

YES if the save succeeds, otherwise NO.

like image 34
David Rönnqvist Avatar answered Sep 24 '22 04:09

David Rönnqvist