我有一个记录,我在本地存储在设备上,我有一个按钮,从本地存储中删除记录。当用户按下按钮时,将调用此方法并在本地从设备中删除记录(通过使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 {
}
}