converting NSDictionary object to NSData object and vice-versa

前端 未结 2 870
难免孤独
难免孤独 2020-12-02 14:51

I have to convert an NSDictionary object into NSData and further I have to get the same NSDictionary out of the NSData ob

2条回答
  •  暖寄归人
    2020-12-02 15:31

    use NSKeyedArchiver

    To convert NSDictionary To NSData

    NSMutableData *data = [[NSMutableData alloc]init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    [archiver encodeObject:YOURDICTIONARY forKey: YOURDATAKEY];
    archiver finishEncoding];
    [data writeToFile:YOURFILEPATH atomically:YES];
    [data release];
    [archiver release];
    

    To get the NSDictionary back from the stored NSData

    NSData *data = [[NSMutableData alloc]initWithContentsOfFile:YOURFILEPATH];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    YOURDICTIONARY = [unarchiver decodeObjectForKey: YOURDATAKEY];
    [unarchiver finishDecoding];
    [unarchiver release];
    [data release];
    

提交回复
热议问题