【问题标题】:Casting void* to NSString* without stringWithCString在没有 stringWithCString 的情况下将 void* 转换为 NSString*
【发布时间】:2010-12-03 19:22:39
【问题描述】:

我有一个与钥匙串交互的程序。你传入一个指向 void 指针的指针,我猜钥匙串将它指向密码,你还传入一个 UInt32 指针,它将指向密码的长度。

然后我需要将它用作 NSString,我尝试直接将其转换为这样,但它聚合了更多位,然后需要,这不适用于密码。我尝试使用:

NSString* password=[NSString stringWithCharacters:passwordData length:passwordLength];

这将密码更改为类似中文的字符。不知道为什么。当我在调试模式下打印描述时,它给了我:

Printing description of password:
\u3039\u4839\u6d6f\u2165\u1566�

我能够让它完美地工作:

NSString* password=[NSString stringWithCString:passwordData length:passwordLength];

但这是贬值的,我想避免使用它。我对 C 和 Objective-C 都很陌生,空指针让我陷入循环。在调试模式下,我查看了指针指向的内存,它肯定在那个内存位置。我尝试使用 const char* 但它不喜欢这样说变量可能尚未初始化。

这是我用来获取钥匙串的方法

- (OSStatus) GetPasswordKeychain:(void*)passwordData length:(UInt32*)passwordLength label:(NSString*)serverName
{
 status=SecKeychainFindGenericPassword(NULL, (UInt32)[serverName length], [serverName UTF8String], usernameLength, username,passwordLength , passwordData, NULL);
return status;
}

有没有办法让 NSString 以正确的长度指向那里并让它成为正确的东西。谢谢您的帮助。这个地方很棒!

【问题讨论】:

    标签: objective-c nsstring keychain void-pointers


    【解决方案1】:

    淘完the Apple website发现了方法:

    - (id)initWithBytes:(const void *)bytes length:(NSUInteger)length encoding:(NSStringEncoding)encoding
    

    而且效果很好。

    【讨论】:

    • 这真的对我有帮助!
    【解决方案2】:

    stringWithCString 已在 10.5 中被贬值,但直到现在我才找到一个不错的替代品:

    消息 = [NSString stringWithCString:(buffer + 4) 长度:(arg2 -5)];

    变成:

    message = [[[NSString alloc] initWithBytes:(buffer + 4) length:(arg2 -5) encoding:NSASCIIStringEncoding] autorelease];

    【讨论】:

      猜你喜欢
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 2018-08-15
      • 2021-10-24
      • 2017-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多