iOS-タイプ変換

1561 ワード

データ型とchar*型の相互変換(NSData char*)

NSData * data;
char * chars = (char *)[data bytes];
Byte * tempData = malloc(sizeof(Byte)*16);
NSData * data = [NSData dataWithBytes:tempData length:16];

文字列タイプとデータ型の相互変換(NSString NSData)

+ (NSData *)dataWithString:(NSString *)string{    
    NSData * data = [string dataUsingEncoding:NSUTF8StringEncoding];    
    return data;
}
+ (NSString *)stringWithData:(NSData *)data{    
    NSString * string = [[NSString alloc] initWithData:dataencoding:NSUTF8StringEncoding];    
    return string;
}

辞書タイプとJSONタイプの相互変換(NSDictionary JSON)

+ (NSDictionary *)dictionaryWithJSON:(NSString *)JSON{    
    if (!JSON)   return nil;    
    NSData * data = [JSON dataUsingEncoding:NSUTF8StringEncoding];    
    NSError * error = nil;    
    NSDictionary * dictionary = [NSJSONSerialization JSONObjectWithData:dataoptions:NSJSONReadingMutableContainers error:&error];    
    if (error) {        
        NSLog(@"JSON :%@",error);        
        return nil;    
    }    
    return dictionary;
}
+ (NSString *)JSONWithDictionary:(NSDictionary *)dictionary{    
    NSError * error = nil;    
    NSData * data = [NSJSONSerialization dataWithJSONObject:dictionaryoptions:NSJSONWritingPrettyPrinted error:&error];    
    NSString * JSON = [[NSString alloc] initWithData:dataencoding:NSUTF8StringEncoding];    
    return JSON;
}