钥匙串访问代码泄漏

时间:2012-09-05 16:12:08

标签: iphone xcode cocoa-touch memory-leaks

这是泄漏: enter image description here

这是我的代码:

+(NSString *)getSecureValueForKey:(NSString *)key {

    // Retrieve a value from the keychain
    NSDictionary *result;
    NSArray *keys = [[[NSArray alloc] initWithObjects: (NSString *) kSecClass, kSecAttrAccount, kSecReturnAttributes, nil] autorelease];
    NSArray *objects = [[[NSArray alloc] initWithObjects: (NSString *) kSecClassGenericPassword, key, kCFBooleanTrue, nil] autorelease];
    NSDictionary *query = [[NSDictionary alloc] initWithObjects: objects forKeys: keys];

    // Check if the value was found
    OSStatus status = SecItemCopyMatching((CFDictionaryRef) query, (CFTypeRef *) &result);
    [query release];
    if (status != noErr) {
        // Value not found
        return nil;
    } else {
        // Value was found so return it
        NSString *value = (NSString *) [result objectForKey: (NSString *) kSecAttrGeneric];
        return value;
        [result release];
    }
}

+(BOOL)storeSecureValue:(NSString *)value forKey:(NSString *)key {
    // Get the existing value for the key
    NSString *existingValue = [self getSecureValueForKey:key];

    // Check if a value already exists for this key
    OSStatus status;
    if (existingValue) {
        // Value already exists, so update it
        NSArray *keys = [[[NSArray alloc] initWithObjects: (NSString *) kSecClass, kSecAttrAccount, nil] autorelease];
        NSArray *objects = [[[NSArray alloc] initWithObjects: (NSString *) kSecClassGenericPassword, key, nil] autorelease];
        NSDictionary *query = [[[NSDictionary alloc] initWithObjects: objects forKeys: keys] autorelease];
        status = SecItemUpdate((CFDictionaryRef) query, (CFDictionaryRef) [NSDictionary dictionaryWithObject:value forKey: (NSString *) kSecAttrGeneric]);
    } else {
        // Value does not exist, so add it
        NSArray *keys = [[[NSArray alloc] initWithObjects: (NSString *) kSecClass, kSecAttrAccount, kSecAttrGeneric, nil] autorelease];
        NSArray *objects = [[[NSArray alloc] initWithObjects: (NSString *) kSecClassGenericPassword, key, value, nil] autorelease];
        NSDictionary *query = [[[NSDictionary alloc] initWithObjects: objects forKeys: keys] autorelease];
        status = SecItemAdd((CFDictionaryRef) query, NULL);
    }

    // Check if the value was stored
    if (status != noErr) {
        // Value was not stored
        return false;
    } else {
        // Value was stored
        return true;
    }
}
你可以帮我解决一下吗?每次我在钥匙串中访问或存储数据时都会发生泄漏。 我没有在没有ARC的情况下编程很多时间,我只是无法跟踪这个泄漏!

谢谢!

1 个答案:

答案 0 :(得分:0)

在创建keys后发布objectsquery,在返回result之前发布value ,实际发布期间创建的新对象你的商店安全价值方法。

此时,你的选择是,了解内存管理实际上是如何工作的,或者只是打开ARC并让它为你处理大部分内容。