繁体   English   中英

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

[英]Write a simple c++ function in objective c

我正在努力使我的生活更轻松一些。 我从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 ++方法?

提前致谢

我想这在技术上是ac函数,是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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM