如何在TextField中显示NSMutableData?

时间:2012-01-22 22:21:51

标签: objective-c

我无法弄清楚为什么以下代码只是生成随机字节并在TextField中将其显示为String不起作用。程序正确编译但它始终显示一个空字符串。 (没有)。问题应该在最后3行,但究竟是什么?

- (NSData *)randomDataOfLength:(size_t)length {

   NSMutableData *data = [NSMutableData dataWithLength:length];

   int result = SecRandomCopyBytes(kSecRandomDefault, 
                                length,
                                data.mutableBytes);
   NSAssert(result == 0, @"Unable to generate random bytes: %d",
         errno);

   unsigned char byteBuffer[[data length]];
   [data getBytes:byteBuffer];

   [textresult setText:[NSString stringWithUTF8String:(char *)byteBuffer]];
   ...

文本结果假定为TextField。

1 个答案:

答案 0 :(得分:1)

试试这个:

- (NSData *)randomDataOfLength:(size_t)length {
    NSMutableData *data = [NSMutableData dataWithLength:length];
    int result = SecRandomCopyBytes(kSecRandomDefault, length, data.mutableBytes);
    NSAssert(result == 0, @"Unable to generate random bytes: %d", errno);

    NSString* str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    [textresult setText:str];