2012-06-07 57 views
0

我试图让我的生活变得更容易一些。我得到了很多的值从NSDictionary中,像这样:在目标c中编写一个简单的C++函数

//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++的方法是什么?

在此先感谢

+4

GetDictValue(myDictionary,@ “值”); [myDictionaryobjectForKey:@“value”]; 他们有相同数量的字符......为什么你认为第一行比第二行更有用? –

+0

我想我需要检查对象是否存在于字典中?该值有时为空 – BlackMouse

+0

@ user1251004在这种情况下,你的C++函数会返回什么? – Stefan

回答

2

我想这是技术上的交流功能,是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; 
    } 
} 
+0

太棒了。正是我需要的。谢谢 – BlackMouse

+0

但是如果[dict objectForKey:key]没有返回任何东西,函数返回什么? –

+0

@MarcoPace:在ARM上,返回值是r0,所以在这种情况下'dict'将被返回,这是不正确的。这个函数也应该处理'else'的情况。 – kfb

1

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

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