O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 = [[NSBundle mainBundle] bundleIdentifier];

NSDictionary *query = @{
        (__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword,
        (__bridge id)kSecAttrService : service,
        (__bridge id)kSecAttrAccount : keyToSearchFor,
        };

Then query for that dictionary and see whether you can find the existing item in the keychain:

OSStatus found = SecItemCopyMatching((__bridge CFDictionaryRef)query,
                                       NULL);

Note

You don’t necessarily have to check for an existing ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required