Claudio Ferraro
Claudio Ferraro

Reputation: 4721

How display an NSMutableData in a TextField?

I cannot figure out why the following code which simply should generate random bytes and displays it as a String in a TextField doesn't work. The program correctly compiles but it shows always a null string. (nothing). The problem should be in the last 3 lines but what exactly ?

- (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]];
   ...

text result is assumed to be a TextField.

Upvotes: 0

Views: 273

Answers (1)

seppo0010
seppo0010

Reputation: 15849

Try this:

- (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];

Upvotes: 1

Related Questions