
前言:
做蓝牙设备的时候,设计到数据的读取和写入,要求写入到数据库,如上图所示,折线画出来是有很多的点来组成的,如何将这些点写入到本地数据库,然后在正确的读取出来是这篇文章的主要内容
首先给出一个封装好的工具,可以 字典/数组 --> JSON ---> 字典/数组:
为了方便以后用到最好是封装成一个工具类MuscleTool如下:
#import <Foundation/Foundation.h>
@interface MuscleTool : NSObject
+(MuscleTool*)sharedInstance;
// String --- > NSArray/NSDictionary
-(id)stringToNSArrayOrNSDictionaryWithString:(NSString *)string;
// JSON-->NSArray
- (NSString *)toJSONData:(id)theData;
@end
#import "MuscleTool.h"
@implementation MuscleTool
+(MuscleTool*)sharedInstance{
static MuscleTool *tool;
static dispatch_once_t toolonce;
dispatch_once(&toolonce, ^{
tool = [[MuscleTool alloc] init];
});
return tool;
}
// JSON字符串 --- > NSArray/NSDictionary
-(id)stringToNSArrayOrNSDictionaryWithString:(NSString *)string
{
NSData* data = [string dataUsingEncoding:NSUTF8StringEncoding];
__autoreleasing NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
// NSArray-->JSON字符串
- (NSString *)toJSONData:(id)theData{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString;
if ([jsonData length] > 0 && error == nil){
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return jsonString;
}else{
return nil;
}
}
@end
具体用法如下:
有了工具类的之后,事情还没做完,因为我所用到存放数据的数组存放的是 CGPoint 坐标类型的,所以还需要进行进一步的处理;
- 把数组转为字符串,然后写入数据库:
NSMutableArray *pointArray = [NSMutableArray array];
for (int i = 0; i < self.LCView.pointArray.count; i ++) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
NSValue *pointObj = self.LCView.pointArray[i];
CGPoint pointRestored = [pointObj CGPointValue];
[dictionary setValue:[NSString stringWithFormat:@"%f",pointRestored.x] forKey:@"x"];
[dictionary setValue:[NSString stringWithFormat:@"%f",pointRestored.y] forKey:@"y"];
[pointArray addObject:dictionary];
}
NSString *dectString = [[MuscleTool sharedInstance] toJSONData:pointArray];
// dectString即为得到的JSON
- 从数据库中/网络读取数据, JSON 字符串转为数组:
NSMutableArray *mutableArr = [NSMutableArray array];
// self.testmodel.dectecttime 是读取到的 JSON 字符串
NSArray *dectArr = [[MuscleTool sharedInstance] stringToNSArrayOrNSDictionaryWithString:self.testmodel.dectecttime];
for (int i = 0; i < dectArr.count; i ++) {
NSDictionary *dict = dectArr[i];
CGPoint point;
point.x = [dict[@"x"] doubleValue];
point.y = [dict[@"y"] doubleValue];
NSValue *pointObj = [NSValue valueWithCGPoint:point];
[mutableArr addObject:pointObj];
}
// mutableArr即为得到的数组,存放的是 CGPoint 类型的坐标
网友评论