守望远方

热爱生活 热爱工作 守望远方
NSData和结构体struct,int相互转换

1. Byte *testByte = (Byte *)[data bytes];

    for(int i=0;i<[data length];i++)

    {

        printf("%c",testByte[i]);

    }

 

用处是当用NSNotification传递数据时需要这个转换,然后把NSData放到userInfo中。

// make a NSData object 
NSData *myData = [NSData dataWithBytes:&myPacketJoin length:sizeof(myPacketJoin)]; 

// make a new PacketJoin 
PacketJoin newJoin; 
[myData getBytes:&newJoin length:sizeof(newJoin)];
 
struct msg { 
        uint32_t msgtype;
        uint32_t param1;
        uint32_t param2;
    };
    struct msg a;
    
    a.msgtype = 123456;
    a.param1 = 12345;
    a.param2 = 12345;
   
    
    struct msg ba;
    NSData *msgData = [[NSData alloc]initWithBytes:&a length:sizeof(a)];
    [msgData getBytes:&ba length:sizeof(ba)];
    
    
    NSLog(@"a:%u", ba.msgtype);
    NSLog(@"ba:%u", a.msgtype );
 

如果你在做mac开发,又涉及到socket编程,那么制作包头的时候你就可能要把int转换成NSData了。看了网上有个人写的方法,把int转换成了nsstring然后再转换成NSData,自欺欺人而已。

下面说说正确的转换方法。

 

int i =1;NSData*data =[NSData dataWithBytes:&i length:sizeof(i)];

 

 

int i;[data getBytes:&i length:sizeof(i)];

 

1. NSData 与 NSString:
NSData-> NSString
NSString *aString = [[NSString alloc] initWithData:adataencoding:NSUTF8StringEncoding];
NSString->NSData
NSString *aString = @"1234abcd";
NSData *aData = [aString dataUsingEncoding: NSUTF8StringEncoding]; 

//将data类型的数据,转成UTF8的数据
+(NSString *)dataToUTF8String:(NSData *)data
{
 NSString *buf = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
 return [buf autorelease];
}

//将string转换为指定编码 
+(NSString *)changeDataToEncodinString:(NSData *)data encodin:(NSStringEncoding )encodin{
    NSString *buf = [[[NSString alloc] initWithData:data encoding:encodin] autorelease];
    return buf;
}

2. NSData 与 UIImage
NSData->UIImage
UIImage *aimage = [UIImage imageWithData: imageData];
 
//例:从本地文件沙盒中取图片并转换为NSData
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *name = [NSString stringWithFormat:@"ceshi.png"];
NSString *finalPath = [path stringByAppendingPathComponent:name];
NSData *imageData = [NSData dataWithContentsOfFile: finalPath];
UIImage *aimage = [UIImage imageWithData: imageData];

 

3.NSData与NSArray  NSDictionary

+(NSString *)getLocalFilePath:(NSString *) fileName
{
 return [NSString stringWithFormat:@"%@/%@%@", NSHomeDirectory(),@“Documents”,fileName];
}

包括将NSData写进Documents目录
从Documents目录读取数据
在进行网络数据通信的时候,经常会遇到NSData类型的数据。在该数据是dictionary结构的情况下,系统没有提供现成的转换成NSDictionary的方法,为此可以通过Category对NSDictionary进行扩展,以支持从NSData到NSDictionary的转换。声明和实现如下:
 
+ (NSDictionary *)dictionaryWithContentsOfData:(NSData *)data {     
    CFPropertyListRef list = CFPropertyListCreateFromXMLData(kCFAllocatorDefault, (CFDataRef)data, kCFPropertyListImmutable, NULL);
    if(list == nil) return nil; 
    if ([(id)list isKindOfClass:[NSDictionary class]]) { 
         return [(NSDictionary *)list autorelease]; 
        } 
    else { 
         CFRelease(list); 
         return nil; 
        } 
}

 

NSData生成:

NSDictionary *dic =[NSDictionary dictionaryWithObject:@"hello" forKey:@"KEY"];

NSData *d = [NSKeyedArchiver archivedDataWithRootObject:dic];

从文件生成NSData:

NSBundle *bundle = [NSBundle mainBundle];

NSString *path = [bundle pathForResource:@"hello"  ofType:@"png"];

NSData *d = [[NSData alloc] initWithContentsOfFile:  path];

 取得元素长度:

int i = [d length];

NSData型转成NSDictionary型:

NSDictionary *reverse = [NSKeyedUnarchiver unarchiveObjectWithData: d];


4.NSData与NSDate

//函数作用 :date根据formatter转换成string
+(NSString*)dateToString:(NSString *)formatter date:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setDateFormat:formatter];
    return[dateFormatter stringFromDate:date];
}

//函数作用 :string类型的时间戳转换成时间
+(NSString*)dateStringToString:(NSString *)dateStr
{
    if ([dateStr isKindOfClass:[NSNull class]]) {
        return nil;
    }
    else{
        NSInteger time = [dateStr intValue];
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
        NSString *timestr = [NSString stringWithFormat:@"%@",date];
        NSRange rang;
        rang.location = 0;
        rang.length = 10;
        NSString *needtime = [timestr substringWithRange:rang];
        return needtime;
    }
}


//函数作用 :将日期从原格式转换成需要的格式
+(NSString*)convertDateFormatter:(NSString*)sourceFormatter 
                  targetFormatter:(NSString*)targetFormatter  
                       dateString:(NSString*)dateString
{   
    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormatter setDateFormat:sourceFormatter];
    NSDate *date = [dateFormatter dateFromString:dateString];
    [dateFormatter setDateFormat:targetFormatter];
    return[dateFormatter stringFromDate:date];
}

//函数作用 :将日期字符串转换成date
+(NSDate *)stringToDate:(NSString *)formatter dateString:(NSString *)dateString{
 NSDateFormatter *dateFormatter= [[[NSDateFormatter alloc] init] autorelease];
 [dateFormatter setDateFormat:formatter];
 return [dateFormatter dateFromString:dateString];
}


//时间戳转换成时间
                NSInteger time = [[dic objectForKey:@"press_date"] intValue];
                NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
                NSString *timestr = [NSString stringWithFormat:@"%@",date];
                NSRange rang;
                rang.location = 0;
                rang.length = 10;
                NSString *needtime = [timestr substringWithRange:rang];

posted on 2013-01-23 10:13  守望远方  阅读(1206)  评论(0编辑  收藏  举报