在目标 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++ 方法?
提前致谢
我想这在技术上是一个 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
相关文章:
- 在c++中用vector填充一个简单的动态数组
- 如何使用 samtools C API 构建一个简单的主.cpp文件
- 为什么一个简单的程序不能立即启动
- C++ - 在我尝试制作一个简单的计算器时有一个"uninitialized local variable y used"警告
- 为什么 MSVC C++编译器将一个简单的 Hello World 扩展为 4000 行汇编?
- 我写了一个简单的矢量程序,在其中我得到了以下输出。你能帮我理解它的输出吗?
- 如何使用 c++ 在命令行中创建一个简单的字符控制器?
- 对于 ~95% 写入/5% 读取线程安全的无序列图,有没有一个简单的解决方案?
- 在C++中创建一个简单的数据包路由器,如何跟踪"客户端"?
- 创建一个简单的前向迭代器,该迭代器在循环缓冲区的"end"处自动换行
- 我已经安装了用于c++编程的升华3,但在编写了一个简单的程序后,我遇到了以下错误
- 如何设置一个简单的CGAL+Qt程序
- 如何在一个简单的C++项目中使用Poco库
- 我创建了一个简单的程序,但有些地方不对劲
- Qt的新信号/时隙语法问题 - 连接到一个简单的函数
- 一个简单的 win32 多线程代码.这能行吗?
- 我正在尝试构建一个简单的程序来从 mysql 数据库中读取信息
- 创建一个简单的计算器,添加时遇到问题
- 我正在编写一个简单的客户端套接字应用程序,但在连接后服务器收到一个空缓冲区
- 为什么一个简单的"Hello World"风格的程序不能用Turbo C++编译?