ios core data how to implement the sql transaction function?

▼魔方 西西 提交于 2020-01-12 18:49:42

问题


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?


回答1:


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.




回答2:


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

[[<#NSManagedObjectContext#> undoManager] undo]; // rollback
...


来源:https://stackoverflow.com/questions/9733233/ios-core-data-how-to-implement-the-sql-transaction-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!