【问题标题】:CFStringRef setting a value to ""CFStringRef 将值设置为“”
【发布时间】:2011-05-12 12:29:57
【问题描述】:

我有一个 CFStringRef 变量,我执行检查以确保它不是 1 特定值。如果是,那么我想将其设置为 @""

的 NSString 等效项

这是代码

CFStringRef data = = CFDictionaryGetValue(dict, kABPersonAddressStateKey);

NSComparisonResult result = [(NSString *)data compare:element options:compareOptions];
if(NSOrderedAscending == result) {
    // Do something here...
}
else if (NSOrderedSame == result) {
    // Do another thing here if they match...
    data = "";
}
else {
    // Try something else...
}

所以在 if else 块中,我想将它设置为 "" 但 Xcode 警告我它是无效的指针类型。

【问题讨论】:

    标签: ios ios4 nsstring cfstring


    【解决方案1】:

    CFStringRef 是不可变对象,因此您必须创建具有不同值的新实例:

    data = CFStringCreateWithCString (NULL, "", kCFStringEncodingUTF8);
    

    请记住,您需要释放该值。

    但由于 CFStringRef 和 NSStrings 类型是免费桥接的,因此您可以在代码中使用 NSString(这可能会让以后更容易理解和支持):

    NSString *data = (NSString*)CFDictionaryGetValue(dict, kABPersonAddressStateKey);
    
    NSComparisonResult result = [(NSString *)data compare:element options:compareOptions];
    if(NSOrderedAscending == result) {
        // Do something here...
    }
    else if (NSOrderedSame == result) {
        // Do another thing here if they match...
        data = @"";
    }
    else {
        // Try something else...
    }
    

    【讨论】:

    • 所以基本上 CFRelease(data) 然后说 data = CFStringCreateWithCString(NULL, "", kCFStringEncodingUTF8)
    • 我认为 CFDictionaryGetValue 返回不保留的字符串,所以你不应该在第一种情况下释放它。但是在您使用 CFStringCreateWithCString 创建数据之后 - 您必须在之后释放它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 2022-12-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多