Monday, March 24, 2014

Converting NSString to NSData and NSData to NSString

Description

Below code segment shows how to convert a NSString value to NSData and NSData value to NSString value. At the beginning, It create a NSString literal with the variable name "firstString" then value of "firstString" variable is taken as a way that can be assigned into NSData variable by using method [1]. The variable "firstString" is assigned with "nil" in order to show that the variable contains nothing. The value of the variable has printed to by using "NSLog". After the printing a NSString object is created with by using previously created NSData. Method [2] has been used. Then the "firstString" value is printed again with NSLog.

  1. - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
  2. - (instancetype)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding


Code

    NSString *firstString = @"This is the string that is wanted to convert";
    
    NSData *dataFromString = [firstString dataUsingEncoding:NSUTF8StringEncoding];
    
    firstString = nil;
    
    NSLog(@"firstString (nil) = %@", firstString);
    
    firstString = [[NSString allocinitWithData:dataFromString encoding:NSUTF8StringEncoding];
    

    NSLog(@"firstString (!nil) = %@", firstString);

Result

2014-03-24 17:10:11.367 TestProject[3048:60b] firstString (nil) = (null)
2014-03-24 17:10:11.369 TestProject[3048:60b] firstString (!nil) = This is the string that is wanted to convert