gpt4 book ai didi

objective-c - 使用 sqlite3 进行类型转换

转载 作者:行者123 更新时间:2023-12-03 19:41:03 28 4
gpt4 key购买 nike

我不是来自 xcode 背景,而是来自 java 和 c#。现在我正在尝试将我的应用程序更改为 ios,但不确定我是否理解如何正确转换,或者更重要的是,什么是 xcodes 问题!

我正在尝试做一些非常简单的事情,从 sqlite 获取值并填充 NSMutableDictionary 对象。

我想获得诸如 long、int 和 string 之类的值,看来我必须进行各种强制转换才能让编译器喜欢它。有人能指出我应该写的正确方向吗,这肯定不是必需的。

在本示例中,我的字典变量称为 myDictionary。

将字符串添加到 NSDictionary

[myDictionary setValue:[[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(sqlStatement, 4)] forKey:@"myText"];

将 int 添加到 NSDictionary
[myDictionary setValue: [[NSNumber alloc] initWithUnsignedInt:sqlite3_column_int(sqlStatement, 0)] forKey:@"myInt" ];

所有这些类型转换真的有必要吗?我以为我可以做这样简单的事情

将 int 添加到 NSDictionary
[myDictionary setValue: sqlite3_column_int(sqlStatement, 0) forKey:@"myInt" ];

但是这句话

Implicit conversion of 'int' to 'id' is disallowed with ARC



也试过
[myDictionary setValue: (int *)sqlite3_column_int(sqlStatement, 0) forKey:@"myInt" ];

但我明白了

Implicit conversion of a non-Objective-C pointer type 'int' to 'id' is disallowed with ARC



我也用文本尝试过同样的事情。如果我没有正确执行此操作,请告诉我。

即使是这样的东西也行不通
int *myVar = sqlite3_column_int(sqlStatement, 0);

如果我也改变它
int myVar = sqlite3_column_int(sqlStatement, 0);

确实有效,然后我无法将其填充到 NSDictionary 中,因为此错误
[myDictionary setValue:myVar forKey:@"intValue"];

最佳答案

是的,一些类型转换是必要的。其中很大一部分是您将 sqlite 的 C 接口(interface)与 Objective C 混合在一起,您必须观察什么是对象,什么是原语。您的第一个示例(字符串)几乎就是这样。 NSString 与 C 的 char * 有很大不同。同样,NSNumber 也跟在它后面。但是请注意,您只进行了一次 Actor 阵容,并且来自

const unsigned char *


char *

NSDictionaries 应该只存储对象,而不是原语,因此您需要放入 NSStrings 和 NSNumbers,而不是 char * 和 int。

您不想将指向原语的指针(例如 (int *) 插入到 NSDictionary 中)先将它们转换为对象,然后在再次获取它们时取消转换。

有一些快捷例程可能对您有所帮助,例如:
[myMutableDictionary setValue: [NSNumber numberWithInt:2] forKey:@"mykey"];

希望这可以帮助。

关于objective-c - 使用 sqlite3 进行类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29215791/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com