我有一条记录在本地存储在设备上,我有一个按钮可以从本地存储中删除记录。当用户按下按钮时,会调用此方法并从本地设备中删除记录(通过使 guid 无效)。我正在使用 Akavache 来保存数据。
虽然这在大多数情况下都有效,但我注意到有时当我删除记录并刷新视图时,记录会从集合中删除。但是,如果注销并重新登录应用程序,记录会重新出现。
我想知道这是否是在本地存储和删除记录的正确方法?
public async Task RemoveFormFromDevice(FormData form)
{
string cacheKey = "data." + form.Guid.ToString ();
await _cache.Invalidate (cacheKey);
await _localStorage.Invalidate (cacheKey);
List<KeyValuePair<Guid, int?>> guids = await _cache.Get<List<KeyValuePair<Guid, int?>>>(CACHE_KEY_PROCS);
if (guids == null)
return;
guids.RemoveAll (a => a.Key == form.Guid);
await _cache.Insert (CACHE_KEY_PROC, guids, null);
await _localStorage.Insert (CACHE_KEY_PROCS, guids, null);
}
编辑:这是我登录应用程序时检索记录的方式:
private async Task<List<FormData>> getSavedProcs()
{
List<FormData> forms = new List<FormData> ();
List<KeyValuePair<Guid, int?>> guids = await _cache.Get<List<KeyValuePair<Guid, int?>>> (CACHE_KEY_PROCS);
if (guids != null)
{
foreach (KeyValuePair<Guid, int?> pair in guids)
{
string cacheKey = "data." + pair.Key.ToString ();
string formJson = await _cache.Get<string> (cacheKey);
FormData form = JsonConvert.DeserializeObject<FormData> (formJson);
if (form != null)
forms.Add (form);
}
}
return forms;
}
public async Task<T> Get<T>(string key) where T : class
{
try
{
return await memoryCache.GetObject<T> (key);
}
catch(KeyNotFoundException ex) {
T localStoreObj = await localStorage.Get<T> (key);
if (localStoreObj != null)
await this.Insert (key, localStoreObj);
return localStoreObj;
}
catch(Exception ex) {
return await Task.FromResult<T> (null);
}
}
public virtual async Task<T> Get<T>(string key) where T : class
{
try
{
return await encryptedCache.GetObject<T> (key);
}
catch(KeyNotFoundException ex) {
return await Task.FromResult<T> (null);
}
catch(Exception ex) {
return await Task.FromResult<T> (null);
}
}
public async Task Insert<T>(string key, T value, DateTimeOffset? expiration = default(DateTimeOffset?)) where T : class
{
try
{
await memoryCache.InsertObject<T> (key, value, expiration);
}
catch {
}
}