下一段代码中有内存泄漏。我从here启发,这是RSA算法的一部分。
- (SecKeyRef)getPublicKeyRef {
OSStatus resultCode = noErr;
SecKeyRef publicKeyReference = NULL;
if(publicKey == NULL) {
NSMutableDictionary * queryPublicKey = [[NSMutableDictionary alloc] init];
NSData *publicTag = [NSData dataWithBytes:publicKeyIdentifier
length:strlen((const char *)publicKeyIdentifier)];
// Set the public key query dictionary.
[queryPublicKey setObject:(id)kSecClassKey forKey:(id)kSecClass];
[queryPublicKey setObject:publicTag forKey:(id)kSecAttrApplicationTag];
[queryPublicKey setObject:(id)kSecAttrKeyTypeRSA forKey:(id)kSecAttrKeyType];
[queryPublicKey setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnRef];
// Get the key.
resultCode = SecItemCopyMatching((CFDictionaryRef)queryPublicKey, (CFTypeRef *)&publicKeyReference);
// NSLog(@"getPublicKey: result code: %d", resultCode);
if(resultCode != noErr)
{
publicKeyReference = NULL;
}
// [publicTag release];
[queryPublicKey release];
} else {
publicKeyReference = publicKey;
}
return publicKeyReference;
}
泄漏仪器表示它正在泄漏:
resultCode = SecItemCopyMatching((CFDictionaryRef)queryPublicKey, (CFTypeRef *)&publicKeyReference);
请告诉我怎么解决这个问题。
答案 0 :(得分:6)
您的方法有时返回一个保留计数为+1的实例,并且您很可能不会在其余代码中释放它。如果调用了SecItemCopyMatching,则返回retain count +1,但是如果设置了publicKey,那么你的函数返回一个值为retain count + -0,这是坏的。
您需要确保始终以相同的保留计数返回。在这种情况下,我会这样做:
} else {
publicKeyReference = publicKey;
CFRetain(publicKeyReference);
}
然后,您的方法的每个调用者都必须确保CFRelease
值...但是这违反了 get 规则(它应该返回保留计数+ -0),所以或许重新命名方法是个好主意。