简体   繁体   中英

Write a simple c++ function in objective c

I'm trying to make life a little bit easier for me. I get a lot of values from NSDictionary, like this:

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

I have a file (Variables.h) where I store a lot of stuff to control the app. If would be nice to put a few helper methods in there. So instead of doing the above code, I would like to have a c++ function in the Variables.h, so I can just do this:

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

How do you write that c++ method?

Thanks in advance

I suppose this is technically ac function, is c++ a strict requirement

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

Consider using id and casting where necessary:

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

Personally, I would rewrite your test like this to get rid of a lookup:

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

But if you want a default value for missing keys and it doesn't have to be a C++ function, I believe the more idiomatic solution would be to use a category to extend NSDictionary.

Thoroughly untested and uncompiled code:

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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