在目标 c 中编写一个简单的 c++ 函数

Write a simple c++ function in objective c

本文关键字:一个 简单 函数 c++ 目标      更新时间:2023-10-16

我正在努力使我的生活更轻松一点。我从NSDictionary中得到很多值,如下所示:

//First, make sure the object exist 
if ([myDict objectForKey: @"value"])
{
     NSString *string = [myDict objectForKey: @"value"]; 
     //Maybe do other things with the string here... 
}

我有一个文件(Variables.h),我在其中存储了很多东西来控制应用程序。如果在那里放一些帮助程序方法会很好。因此,我希望在 Variables.h 中有一个 c++ 函数,而不是执行上述代码,所以我可以这样做:

NSString *string = GetDictValue(myDictionary, @"value"); 

你如何编写这个 c++ 方法?

提前致谢

我想这在技术上是一个 c 函数,c++ 是一个严格的要求吗

static NSString* GetDictValue(NSDictionary* dict, NSString* key)
{
    if ([dict objectForKey:key])
    {
         NSString *string = [dict objectForKey:key]; 
         return string;
    }
    else 
    {
        return nil;
    }
}

必要时考虑使用id和强制转换:

static id GetDictValue(NSDictionary* dict, NSString* key)
{
    if ([dict objectForKey:key])
    {
         id value = [dict objectForKey:key]; 
         return value;
    }
    else 
    {
        return nil;
    }
}

就个人而言,我会像这样重写您的测试以摆脱查找:

NSString *string = [myDict objectForKey: @"value"]; 
if (string)
{
     // Do stuff.
}

但是,如果您想要丢失键的默认值,并且它不必是C++函数,我相信更惯用的解决方案是使用类别来扩展 NSDictionary。

完全未经测试和编译的代码:

@interface NSDictionary (MyNSDictionaryExtensions)
- (NSString*) objectForKey: (NSString*) key withDefaultValue: (NSString*) theDefault;
- (NSString*) safeObjectForKey: (NSString*) key;
@end
@implementation NSDictionary (MyNSDictionaryExtensions)
- (NSString*) objectForKey: (NSString*) key withDefaultValue: (NSString*) theDefault
{
    NSString* value = (NSString*) [self objectForKey: key];
    return value ? value : theDefault;
}
- (NSString*) safeObjectForKey: (NSString*) key
{
    return [self objectForKey: key withDefaultValue: @"Nope, not here"];
}
@end
相关文章: