3

我对似乎运行良好的 iOS Keychain API 有一个抽象。基本上,它有:

public string GetGenericPasswordField(string account)
{
    var record = SecKeyChain.QueryAsRecord(query, out code);
    if (code == SecStatusCode.ItemNotFound)
        return null;
    return NSString.FromData(record.ValueData, NSStringEncoding.UTF8);
}

public void SetGenericPasswordField(string account, string value)
{
    if (value == null)
    {
        SecKeyChain.Remove(record);
        return;
    }
    var record = new SecRecord (SecKind.GenericPassword) {
        Service = service,
        Label = label,
        Account = account,
        ValueData = NSData.FromString (value),
    };
    SecStatusCode code = SecKeyChain.Add (record);
    if (code == SecStatusCode.DuplicateItem)
    {
        // (remove and re-add item)
    }
}

我在我的应用程序的设置屏幕上使用了这个抽象来在离开时保存值,然后在应用程序的其他地方加载这些值。

但是我遇到了一个问题,如果您不离开当前的 ViewController,保存值似乎不会生效。我正在做的类似于:

if (Keychain.GetGenericPasswordField("RemoteLogin") == null)
{
    var remotePassword = GetFromDialog();
    Keychain.SetGenericPasswordField("RemoteLogin", Hash(remotePassword));
    // Safe to assume the RemoteLogin password got saved, right?
}

// Later on...

if (Keychain.GetGenericPasswordField("RemoteLogin") == null)
{
    // This block is being executed
}

我已经在调试器中逐步检查了代码,以确认事情与我描述的一样,并且我的抽象方法确实得到了SecStatusCode.ItemNotFound支持,这意味着 null 是要返回的适当值。

我曾经通过将前半部分代码移回之前的 ViewController 来解决这个问题,出于某种原因,这似乎唤醒了它,或者清除了正在发生的任何缓存。但是现在我遇到了另一种不太实际的情况。

为什么会这样?我的抽象是否泄漏?

4

0 回答 0