NSString initWithBytes:length:encoding:

Code Snippets and Hints: NSString instance methods

NSString initWithBytes:length:encoding instance method. A quick example. Uses a NSData object from the content of my blog’s first page and displays the string in an NSTextView outlet:

- (void)awakeFromNib
{
    ALATest();
    myURL = [NSURL URLWithString:@"http://www.alauda.ro"];
    myData = [NSData dataWithContentsOfURL:myURL];
    myString = [[NSString alloc] initWithBytes:[myData bytes] length:[myData length] encoding:NSASCIIStringEncoding];
#ifdef DEBUG
    NSLog(@"Data is: %@", myString);
#endif

    [_myTextView setString:myString];
}

// memory cleanup
- (void)dealloc
{
    [myString release];
    [super dealloc];
}

The result:

NSString initWithBytes

A variant, with a char array:

- (void)awakeFromNib
{
    //myURL = [NSURL URLWithString:@"http://www.alauda.ro"];
    //myData = [NSData dataWithContentsOfURL:myURL];

    char myChar[] = {"Testing"};

    myString = [[NSString alloc] initWithBytes:myChar length:sizeof(myChar) encoding:NSASCIIStringEncoding];

#ifdef DEBUG
    NSLog(@"Data is: %@", myString);
#endif
    [_myTextView setString:myString];
}

// memory cleanup
- (void)dealloc
{
    [myString release];
    [super dealloc];
}

The result:

Using a char

 
 

Leave a Reply

Your email address will not be published. Required fields are marked *