Saturday, May 18, 2013

NSString initWithData example ios


initWithData: encoding:

Returns an NSString object initialized by converting given data into Unicode characters using a given encoding.
- (id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding
Parameters
data
An NSData object containing bytes in encoding and the default plain text format (that is, pure content with no attributes or other markups) for that encoding.
encoding
The encoding used by data.
Return Value of [NSString initWithData]
An NSString object initialized by converting the bytes in data into Unicode characters using encoding. The returned object may be different from the original receiver. Returns nil if the initialization fails for some reason (for example if datadoes not represent valid data for encoding).
Example of [NSString initWithData]
NSString to NSData:
NSString* str= @"teststring";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
NSData to NSString:
NSString* newStr = [[NSString alloc] initWithData:theData
                                         encoding:NSUTF8StringEncoding];
Example of [NSString initWithData]
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
    [receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString * result_string=[[[NSString alloc] initWithData:receivedData encoding:NSNonLossyASCIIStringEncoding] autorelease];
    NSLog(result_string);
    //...
}
Example of [NSString initWithData]
SomeClass *someObject;
NSString *stringReply;
stringReply = [[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding];
[someObject methodWithString:stringReply];