8.4. Updating Existing Values in the Keychain
Problem
You have already stored a value in the keychain but now want to update it to a new value.
Solution
Given that you have been able to find the value in the keychain
(see Recipe 8.3), you can issue
the SecItemUpdate function with your
query dictionary as its first parameter and a dictionary describing the
change that you want to make to the existing value as its second
parameter. Usually this update dictionary (the second parameter to the
method) contains just one key (kSecValueData) and the value of this
dictionary key is the data to set for the existing key in the
keychain.
Discussion
Let’s assume that, following the advice given in Recipe 8.2, you have stored the string
Steve Jobs with the key of Full
Name in your app’s keychain but want to update that value
now. The first thing that you have to do is find out whether the
existing value is already in the keychain. For that, construct a simple
query, as we have seen earlier in this chapter:
NSString*keyToSearchFor=@"Full Name";NSString*service=[[NSBundlemainBundle]bundleIdentifier];NSDictionary*query=@{(__bridgeid)kSecClass:(__bridgeid)kSecClassGenericPassword,(__bridgeid)kSecAttrService:service,(__bridgeid)kSecAttrAccount:keyToSearchFor,};
Then query for that dictionary and see whether you can find the existing item in the keychain:
OSStatusfound=SecItemCopyMatching((__bridgeCFDictionaryRef)query,NULL);
Note
You don’t necessarily have to check for an existing ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access