Tuesday, May 14, 2013

NSString initWithBytes example ios


initWithBytes: length: encoding:

Returns an initialized NSString object containing a given number of bytes from a given buffer of bytes interpreted in a given encoding.
- (id)initWithBytes:(const void *)bytes length:(NSUInteger)length encoding:(NSStringEncoding)encoding
Parameters of [NSString initWithBytes]
bytes
A buffer of bytes interpreted in the encoding specified by encoding.
length
The number of bytes to use from bytes.
encoding
The character encoding applied to bytes.
Return Value of [NSString initWithBytes]
An initialized NSString object containing length bytes from bytes interpreted using the encoding encoding. The returned object may be different from the original receiver.
Example of [NSString initWithBytes]
@interface NSString (stringWithBytes)

+ (NSString*)stringWithBytes:(const void *)bytes length:(NSUInteger)length encoding:(NSStringEncoding)encoding;

@end

@implementation NSString (stringWithBytes)

+ (NSString*)stringWithBytes:(const void *)bytes length:(NSUInteger)length encoding:(NSStringEncoding)encoding {
    NSString * aString = [[NSString alloc] initWithBytes:bytes length:length encoding:encoding];
    return [aString autorelease];
}

@end
Example of [NSString initWithBytes]
const char* c_string = "012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789";
NSString *string = [[[NSString alloc] initWithBytes:c_string
                                             length:strlen(c_string)
                                           encoding:NSUTF8StringEncoding] autorelease];
assert([string length] == strlen(c_string)); // only valid for ASCII
Example of [NSString initWithBytes]
#import <Foundation/Foundation.h>

int
main()
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    char ary[] = { 116, 101, 115, 116, 255 };

    NSString *s = [[NSString alloc] initWithBytes: ary length: 5 encoding: NSASCIIStringEncoding];
    NSString *s2 = [[NSString alloc] initWithBytes: ary length: 5 encoding: NSUTF8StringEncoding];
    NSLog(@"s: %@, s2: %@", s, s2);

    [pool release];
}