@@ -31,6 +31,53 @@ extension ParseObjectOffline on ParseObject {
3131 print ('Saved object ${objectId ?? "(no objectId)" } to local cache for $parseClassName ' );
3232 }
3333
34+ /// Save a list of objects to local storage efficiently.
35+ static Future <void > saveAllToLocalCache (String className, List <ParseObject > objectsToSave) async {
36+ if (objectsToSave.isEmpty) return ;
37+
38+ final CoreStore coreStore = ParseCoreData ().getStore ();
39+ final String cacheKey = 'offline_cache_$className ' ;
40+ final List <String > cachedStrings = await _getStringListAsStrings (coreStore, cacheKey);
41+
42+ // Use a Map for efficient lookup and update of existing objects
43+ final Map <String , String > objectMap = {};
44+ for (final s in cachedStrings) {
45+ try {
46+ final jsonObj = json.decode (s);
47+ final objectId = jsonObj['objectId' ] as String ? ;
48+ if (objectId != null ) {
49+ objectMap[objectId] = s; // Store the original JSON string
50+ }
51+ } catch (e) {
52+ print ('Error decoding cached object string during batch save: $e ' );
53+ }
54+ }
55+
56+ int added = 0 ;
57+ int updated = 0 ;
58+
59+ // Update the map with the new objects
60+ for (final obj in objectsToSave) {
61+ final objectId = obj.objectId;
62+ if (objectId != null ) {
63+ if (objectMap.containsKey (objectId)) {
64+ updated++ ;
65+ } else {
66+ added++ ;
67+ }
68+ // Encode the new object data and replace/add it in the map
69+ objectMap[objectId] = json.encode (obj.toJson (full: true ));
70+ } else {
71+ print ('Skipping object without objectId during batch save for $className ' );
72+ }
73+ }
74+
75+ // Convert the map values back to a list and save
76+ final List <String > updatedCachedStrings = objectMap.values.toList ();
77+ await coreStore.setStringList (cacheKey, updatedCachedStrings);
78+ print ('Batch saved to local cache for $className . Added: $added , Updated: $updated , Total: ${updatedCachedStrings .length }' );
79+ }
80+
3481 /// Remove this object from local storage (CoreStore).
3582 Future <void > removeFromLocalCache () async {
3683 final CoreStore coreStore = ParseCoreData ().getStore ();
0 commit comments