iOS 对象信息保存、转化JSON、JSON生成对象的模型方案记录

2023-11-17

目标:

将对象的一些信息提取保存起来,然后转化成JSON,再上传到服务器,或其他保存本地的用途。

从服务器接收或从本地读取,然后通过JSON的信息生成指定的对象。


方案代码:

//
//  KeepLabelInfoModel.h
//  TestViewXIB
//
//  Created by yococo on 15/9/29.
//  Copyright (c) 2015年 yococo. All rights reserved.
//

#import <Foundation/Foundation.h>

#import <UIKit/UIKit.h>

@interface KeepLabelInfoModel : NSObject

/***************************/
//记录当前所保存的数据信息
@property(nonatomic,strong,readonly) NSMutableArray* infoArray;


/***************************/
//记录指定对象,内部自行提取需要保存的数据信息
- (void) addObject:(UILabel*)anObject;


/***************************/
//将指定的数据信息数组转换成JSON 字符串格式
@property(nonatomic,readonly) NSString* JSONString;

//将指定的数据信息数组转换成JSON 数据格式
@property(nonatomic,readonly) NSData* JSONData;


/***************************/
//内部处理间的错误情况
@property(nonatomic,strong) NSError* error;


/***************************/
//通过获取指定数据信息生成指定对象
- (void) modelObjectsWithJSONString:(NSString*)jsonString;

- (void) modelObjectsWithJSONData:(NSData*)jsonData;

//记录所生成的对象
@property(nonatomic,strong,readonly) NSArray* modelObjects;


@end


//
//  infoLabelInfoModel.m
//  TestViewXIB
//
//  Created by yococo on 15/9/29.
//  Copyright (c) 2015年 yococo. All rights reserved.
//

#import "KeepLabelInfoModel.h"

@implementation KeepLabelInfoModel

- (void) dealloc
{
    _infoArray = nil;
    _error = nil;
    _modelObjects = nil;
}

- (void) addObject:(UILabel*)anObject
{
    if (_infoArray == nil) {
        _infoArray = [NSMutableArray array];
    }
    
    if (anObject == nil || [anObject isKindOfClass:[UILabel class]] == NO) {
        return;
    }
    
    NSMutableDictionary* tempDictionary = [NSMutableDictionary dictionary];
    [tempDictionary setObject:anObject.text forKey:@"text"];
    [tempDictionary setObject:NSStringFromCGRect(anObject.frame) forKey:@"frame"];
    [tempDictionary setObject:NSStringFromCGAffineTransform(anObject.transform) forKey:@"transform"];
    [tempDictionary setObject:[self getHSBAStringByColor:anObject.textColor] forKey:@"textColor"];
    [_infoArray addObject:tempDictionary];
    
}

- (NSString*) JSONString
{
    if (_infoArray == nil) {
        return nil;
    }
    
    NSError* tempError = nil;
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:_infoArray options:NSJSONWritingPrettyPrinted error:&tempError];
    
    if (tempError == nil) {
        NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        return jsonString;
    }
    
    self.error = tempError;
    
    return nil;
}


- (NSData*) JSONData
{
    if (_infoArray == nil) {
        return nil;
    }
    
    NSError* tempError = nil;
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:_infoArray options:NSJSONWritingPrettyPrinted error:&tempError];
    
    if (tempError == nil) {
        return jsonData;
    }
    
    self.error = tempError;
    
    return nil;
}



- (void) modelObjectsWithJSONData:(NSData *)jsonData
{
    if (jsonData == nil) {
        return;
    }
    
    NSError* tempError = nil;
    
    NSArray* tempArr = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&tempError];
    
    if (tempError) {
        self.error = tempError;
        return;
    }
    
    if (tempArr == nil || [tempArr isKindOfClass:[NSArray class]] == NO) {
        return;
    }
    
    NSMutableArray* tempArray = [NSMutableArray array];
    
    for (NSDictionary* tempDictionary in tempArr) {
        if ([tempDictionary isKindOfClass:[NSDictionary class]]) {
            UILabel* tempLabel = [[UILabel alloc] init];
            
            NSString* tempText = tempDictionary[@"text"];
            if (tempText && [tempText isKindOfClass:[NSString class]]) {
                tempLabel.text = tempText;
            }
            
            NSString* tempFrame = tempDictionary[@"frame"];
            if (tempFrame && [tempFrame isKindOfClass:[NSString class]]) {
                tempLabel.frame = CGRectFromString(tempFrame);
            }
            
            NSString* tempTransform = tempDictionary[@"transform"];
            if (tempTransform && [tempTransform isKindOfClass:[NSString class]]) {
                tempLabel.transform = CGAffineTransformFromString(tempTransform);
            }
            
            NSString* tempTextColor = tempDictionary[@"textColor"];
            if (tempTextColor && [tempTextColor isKindOfClass:[NSString class]]) {
                tempLabel.textColor = [self colorWithHSBAString:tempTextColor];
            }
            
            [tempArray addObject:tempLabel];
        }
    }
    
    _modelObjects = tempArray;
}



- (void) modelObjectsWithJSONString:(NSString*)jsonString
{
    if (jsonString == nil) {
        return;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    [self modelObjectsWithJSONData:jsonData];
}







- (NSString *)getHSBAStringByColor:(UIColor *)originColor {
    NSDictionary *hsbaDict = [self getHSBAValueByColor:originColor];
    return [NSString stringWithFormat:@"(%0.2f, %0.2f, %0.2f, %0.2f)",
            [hsbaDict[@"H"] floatValue],[hsbaDict[@"S"] floatValue],[hsbaDict[@"B"] floatValue],[hsbaDict[@"A"] floatValue]];
}

- (NSDictionary *)getHSBAValueByColor:(UIColor *)originColor
{
    CGFloat h=0,s=0,b=0,a=0;
    if ([originColor respondsToSelector:@selector(getHue:saturation:brightness:alpha:)]) {
        [originColor getHue:&h saturation:&s brightness:&b alpha:&a];
    }
    return @{@"H":@(h),@"S":@(s),@"B":@(b),@"A":@(a)};
}

- (UIColor *) colorWithHSBAString:(NSString*)aColorString
{
    if (aColorString == nil) {
        return nil;
    }
    
    NSString* tempString = [aColorString stringByReplacingOccurrencesOfString:@"(" withString:@""];
    tempString = [aColorString stringByReplacingOccurrencesOfString:@")" withString:@""];
    NSArray* tempArray = [tempString componentsSeparatedByString:@","];
    if (tempArray && tempArray.count == 4) {
        return [UIColor colorWithHue:[tempArray[0] floatValue] saturation:[tempArray[1] floatValue] brightness:[tempArray[2] floatValue] alpha:[tempArray[3] floatValue]];
    }
    return nil;
}

@end



通过 Button 以及 Storyboard 上的Label进行测试


1.获取 Label 的信息

    KeepLabelInfoModel* tempModel = [[KeepLabelInfoModel alloc] init];
    
    for (UILabel* subview in self.view.subviews) {
        if ([subview isKindOfClass:[UILabel class]]) {
            
            [tempModel addObject:subview];
        }
    }
    NSLog(@"%@",tempModel.JSONString);

2.删除 Storyboard 上的 Label

    for (UILabel* subview in self.view.subviews) {
        if ([subview isKindOfClass:[UILabel class]]) {
            [subview removeFromSuperview];
        }
    }

3.校验生成对象情况

    NSString* tempString = @"["
    "{"
    "\"textColor\" : \"(0.00, 0.00, 0.67, 1.00)\","
    "\"frame\" : \"{{104, 380}, {134, 35}}\","
    "\"text\" : \"123\","
    "\"transform\" : \"[1, 0, 0, 1, 0, 0]\""
    "},"
    "{"
    "\"textColor\" : \"(0.00, 0.96, 1.00, 1.00)\","
    "\"frame\" : \"{{273, 276}, {29, 21}}\","
    "\"text\" : \"234\","
    "\"transform\" : \"[1, 0, 0, 1, 0, 0]\""
    "},"
    "{"
    "\"textColor\" : \"(0.00, 0.00, 1.00, 1.00)\","
    "\"frame\" : \"{{150, 498}, {29, 21}}\","
    "\"text\" : \"567\","
    "\"transform\" : \"[1, 0, 0, 1, 0, 0]\""
    "},"
    "{"
    "\"textColor\" : \"(0.00, 0.00, 0.00, 1.00)\","
    "\"frame\" : \"{{217, 405}, {29, 21}}\","
    "\"text\" : \"346\","
    "\"transform\" : \"[1, 0, 0, 1, 0, 0]\""
    "},"
    "{"
    "\"textColor\" : \"(0.18, 0.74, 1.00, 1.00)\","
    "\"frame\" : \"{{273, 498}, {29, 21}}\","
    "\"text\" : \"498\","
    "\"transform\" : \"[1, 0, 0, 1, 0, 0]\""
    "},"
    "]";
    
    
    KeepLabelInfoModel* tempModel = [[KeepLabelInfoModel alloc] init];
    
    [tempModel modelObjectsWithJSONString:tempString];
    
    for (UIView* subview in tempModel.modelObjects) {
        if ([subview isKindOfClass:[UIView class]]) {
            [self.view addSubview:subview];
        }
    }




本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

iOS 对象信息保存、转化JSON、JSON生成对象的模型方案记录 的相关文章

  • 将 C 转换为 Swift:向 UITextField 添加放大镜图标

    如何在左侧添加一个放大镜图标UITextField 我找到了类似问题的答案here https stackoverflow com questions 11811705 where can i get the magnifying glas
  • 如何使用 iOS 可达性

    我正在开发一个使用网络的 iPhone 应用程序 iPhone 通过 HTTP 请求与我的服务器通信 并且应该可以在 WiFi 和 3G 上运行 我目前使用NSURLConnection initWithRequest向我的服务器发送异步请
  • Swift 3:如何访问48字节CFData中matrix_float3x3的值?

    我正在尝试访问内在矩阵answer https stackoverflow com a 48159895 9296667 通过运行下面的命令 我能够得到一个 48 字节的任意对象 https developer apple com docu
  • 使用 Protobuf-net,我收到有关 List 未知线路类型的异常

    我已经开始将 Unity iOS 游戏转换为使用 Protobuf net 保存状态 看起来一切正常 直到我将此实例变量添加到GameState ProtoMember 10 public List
  • 如何在 Swift 中将文件名与文件扩展名分开?

    给定包中文件的名称 我想将该文件加载到我的 Swift 应用程序中 所以我需要使用这个方法 let soundURL NSBundle mainBundle URLForResource fname withExtension ext 无论
  • NSString stringWithContentsOfFile 失败,错误代码似乎错误

    我正在尝试将文件加载到字符串中 这是我正在使用的代码 NSError error nil NSString fullPath NSBundle mainBundle pathForResource filename ofType html
  • 无法连接到 iTunes Store(获取应用内购买列表)

    我正在尝试从我的应用程序的应用程序内购买项目商店中获取列表 这是我所做的 安装了新的配置文件并启用了应用内购买 替换配置文件很棘手 但我认为我的设置是正确的 验证税务和银行信息是否正常 该应用程序已在商店出售 创建测试用户 在测试设备上以测
  • 如何找到键盘未覆盖的视图部分(UIModalPresenationStyleFormSheet)?

    我有一个视图控制器 显示带有 UITextView 的视图 并且我想在键盘出现时调整视图的大小 以便 UITextView 不会被键盘覆盖 我几乎在所有情况下都可以正常工作 据我所知 仅当视图控制器以 ModalPresentationSt
  • .showsPhysics 内存泄漏

    我最近花了 5 个小时尝试调试 Spritekit 应用程序中的内存泄漏 应用程序启动后 我注意到内存使用量略有上升 我花了 5 个小时中的 3 个小时挖掘参考资料 了解强与弱的关系ARC https developer apple com
  • locationOfTouch 和 numberOfTouches

    你好 我有这个识别器 设置为 2 次触摸 但它只返回一个 而不是两个 CGPoint void gestureLoad UIGestureRecognizer recognizer recognizer UITapGestureRecogn
  • 将自定义数据包含到 iOS 故障转储中

    你好 堆栈溢出 有一个简单的问题要问您 当我的应用程序在用户的设备上崩溃时 是否可以将自定义错误数据嵌入到自动生成的 iOS 故障转储中 例如 我的 SQlite 数据库由于某种原因无法运行 例如 数据库文件已损坏 我无法从这个错误中恢复
  • iOS 中 NSDecimalNumber 的小数分隔符错误

    我尝试通过以下方式输出具有正确的小数分隔符的十进制数的描述 NSString strValue 9 94300 NSDecimalNumber decimalNumber NSDecimalNumber decimalNumberWithS
  • 使用未解析的标识符“FlurryAdInterstitial”

    我正在尝试整合Flurry Interstitial Ads使用cocoapods in Swift and Xcode 7 1 1 我正在关注开发人员雅虎网站上的此文档 https developer yahoo com flurry d
  • iOS 7 上 Safari 浏览器的用户代理

    我只想在带有 Safari 浏览器的 iPhone 和 iPod 中打开我的网站 对于 Chrome Dolphin 等任何其他浏览器 它不应该打开 但目前我从几乎所有设备获得相同的用户代理 对于Safari User Agent Stri
  • watchOS 错误:控制器接口描述中的未知属性

    我将 WKInterfacePicker 添加到情节提要中 并将其连接到界面控制器中的 IBOutlet 运行应用程序时 它在控制台中显示一条错误消息 控制器的接口描述 watchPicker 中的未知属性 Code interface I
  • 如何在代码中编辑约束

    我有一个以 100 开始宽度限制的网页 当用户单击按钮时 我想将约束更改为 200 我试过这个 NSLayoutConstraint constrain NSLayoutConstraint constraintWithItem self
  • TableViewController 的 viewDidLoad 未触发

    我一直在关注这个tutorial http www appcoda com ios programming sidebar navigation menu 有一个滑出式菜单 我添加了一个 TableViewController 它将显示文章
  • 模态转场需要点击 2 次而不是 1 次

    我的 UITableView 需要点击 2 次才能显示所选单元格的详细信息页面 一次用于选择 另一次用于显示详细信息视图 我希望有一个 CLI 直接显示所单击单元格的详细视图 我在 UITableViewManager m 中使用此方法的模
  • 更改 iOS7 中 UIAlertView 的字体大小

    我想更改alertView中消息文本和标题文本的字体大小 苹果网站上没有任何文档谈到这一点 但苹果在其子类注释中表示 UIAlertView 类旨在按原样使用 请参考以下链接 https developer apple com librar
  • ios - 如何声明静态变量? [复制]

    这个问题在这里已经有答案了 C 中声明的静态变量如下 private const string Host http 80dfgf7c22634nbbfb82339d46 cloudapp net private const string S

随机推荐

  • playwright自动化项目搭建

    具备功能 关键技术 pylaywright测试库 pytest单元测试框架 pytest playwright插件 非关键技术 pytest html插件 pytest rerunfailures插件 seldom 测试框架 实现功能 元素
  • 静态链接原理以及过程

    通常程序的编译中 或多或少会调用其它库中的函数接口 本篇blog就是讲静态库的调用流程 通常我们知道编译一个可执行程序会有这四个过程 预处理 编译 汇编以及链接 前面三步就是产生目标文件 o的过程 链接就是把各个 o文件粘在一起 构成一个可
  • 杂项设备(misc device)和字符设备(char device)区别

    杂项设备 misc device 杂项设备也是在嵌入式系统中用得比较多的一种设备驱动 在 Linux 内核的include linux目录下有Miscdevice h文件 要把自己定义的misc device从设备定义在这里 其实是因为这些
  • Go语言基础面试题

    一 选择题 1 关于异常设计 下面说法正确的是 A 在程序开发阶段 坚持速错 让程序异常崩溃 开发 测试 准生产 生产 B 在程序部署后 应恢复异常避免程序终止 C 一切皆错误 不用进行异常设计 D 对于不应该出现的分支 使用异常处理 参考
  • 2021-08-03训练记录

    2021 08 03训练记录 Magic Line String Invasion A B C 小biu放牛 小A的游戏 A B C Magic Line 样例输入 1 4 0 1 1 0 1 0 0 1 样例输出 1 999000000
  • 原始GPS与百度、谷歌、高德地图的相互转换(c语言转换)

    原始GPS与百度 谷歌 高德地图的相互转换 c语言转换 原始GPS与百度 谷歌 高德地图的相互转换 1 介绍三种坐标系 2 WGS84 GCJ02 BD09之间的相互转换 C语言实现 原始GPS与百度 谷歌 高德地图的相互转换 1 介绍三种
  • centos 7中NGINX负载均衡(最详细)

    环境 centos7 192 168 186 140 负载均衡 centos7 192 168 186 141 web端 centos7 192 168 186 142 web端 1 关闭防火墙与setenforce web端也要执行 ro
  • json 模块:处理 JSON 数据

    JSON JavaScript Object Notation 是一种轻量级的数据交换格式 易于人阅读和编写 同时也易于机器解析和生成 JSON 基础 JSON 的基础结构有两种 键值对 name value pairs 和数组 array
  • VS编译程序缺失msvcp140d.dll、vcruntime140d.dll和ucrtbased.dll解决方法

    今天编译的一个程序到客户现场电脑上运行闪退 查看发现缺少msvcp140d dll vcruntime140d dll以及ucrtbased dll 总结一下解决办法 供大家参考 方式一 找到对应的 msvcp140d dll vcrunt
  • Java的SSH连接远程服务器

    在我们的示例中 我们将首先打开SSH连接 然后执行一个命令 读取输出并将其写入控制台 最后关闭SSH连接 我们将使示例代码尽可能简单 2 JSch JSch 是SSH2的Java实现 它使我们可以连接到SSH服务器并使用端口转发 X11转发
  • 记几个数据查询语句

    查看某用户所在的表空间SELECT USERNAME DEFAULT TABLESPACE FROM DBA USERS WHERE USERNAME GISAP 查看用户表分区select from user tab partitions
  • java中 instanceof 关键字 作用 和 实际用途

    instanceof 闲聊一下 所谓看书只看前三章 基础java决定上限 所以说基础很重要 Java也是基础扎实决定你的上限 1 instanceof 是Java中的一个关键字 Java中的关键子都是小写 2 instanceof关键字的作
  • 【不忘初心】Windows11 22000.652 X64 四合一[纯净精简版][2.68G](2022.5.3)

    此版可正常更新补丁关闭按流量计费 WIN11全新的UI界面出炉 可以说这一次Windows 11全新升级 无论是从Logo上还是UI界面设计 都有很大的变化 母版来自UUP WIN11 22000 652 为了保证稳定初心的系统全部都是离线
  • 【模拟集成电路】电荷泵(CP)设计

    电荷泵 CP 设计 前言 一 电荷泵 CP 原理 1 电流失配问题 2 开关管的时钟馈通问题 3 电荷注入问题 二 电荷泵 CP 电路 三 电荷泵性能测试 测试原理图 充电测试 放电测试 参考文献 各部分链接链接 前言 本文主要内容是对电荷
  • NLP 算法工程师面试问答-DeepLearningAlgorithm

    关于生成对抗网络GAN 那些你不知道的事 一 动机 之前我们提到玻尔兹曼机 Boltzmann machine 波尔茨曼机作为一种基于能量函数的概率模型 因为能量函数比较复杂 所以存在较多的限制 虽然受限玻尔兹曼机 Restricted B
  • C#通过读取appconfig文件连接数据库

    以Oracle为例 C 连接数据库的时候 需要一些连接字符串 一开始写在程序中 这样会有两个问题 通用性不太好 如果程序具有普遍性 但是连接字符串写死了 每次替换很麻烦 一个工程有很多个项目 每个项目都需要连接字符串 每次更改或者设置也很麻
  • 手机一键制作u盘启动盘_老毛桃U盘启动盘制作教程

    制作前准备 1 准备一个U盘 建议U盘内存8G以上 因为制作时会格式化 请注意备份U盘原资料 2 下载老毛桃U盘装机工具套装 官网 www laomaotao net 老毛桃U盘装机工具下载链接 www laomaotao net 制作过程
  • django 报错:urllib3.exceptions.ConnectTimeoutError 问题解决方法

    问题描述 django项目运行时报错 urllib3 exceptions ConnectTimeoutError
  • opkg 更新软件

    opkg 不同的版本存在不同的配置文件 一般常用的是 etc opkg conf etc opkg customfeeds conf 和 etc opkg distfeeds conf三个 这三个配置文件将会影响opkg运行时软件资源的取向
  • iOS 对象信息保存、转化JSON、JSON生成对象的模型方案记录

    目标 将对象的一些信息提取保存起来 然后转化成JSON 再上传到服务器 或其他保存本地的用途 从服务器接收或从本地读取 然后通过JSON的信息生成指定的对象 方案代码 KeepLabelInfoModel h TestViewXIB Cre