使用以下模型作为示例,在 JSONModel 中处理多态性的最佳实践是什么? ?
@interface GameModel : JSONModel
@property (nonatomic, assign) long id;
@property (nonatomic, assign) NSArray<GameEventModel> *events;
/*
...
*/
@end
@interface GameEventModel : JSONModel
@property (nonatomic, assign) long long timestamp;
/*
...
*/
@end
@interface GameTouchEventModel : GameEventModel
@property (nonatomic, assign) CGPoint point;
/*
...
*/
@end
当 GameModel 使用 {id:1, events:[{point:{x:1, y:1}, timestamp:...}]} 的 JSON 字符串启动时p>
JSONModel 将使用 GameEventModel 并忽略 point 属性。
使用包含type 属性和info 属性的通用GameEventModel 是否更好,例如...
@interface GameTouchEventModel : GameEventModel
@property (nonatomic, strong) NSString *type;
@property (nonatomic, strong) NSDictionary *info;
@end
因此模型可以接受 JSON 作为 {id:1, events:[{ type:"GameTouchEventModel", info:{ point:{x:1, y:1}, timestamp:... } }]}
这种方法的问题是代码更难阅读,并且没有编译器警告/错误等。
在JSONModel中没有办法使用多态模型吗?
最佳答案
我们通过对 JSONModel.m 进行 2 次小改动解决了这个问题,引入了一个新的特殊 JSON 属性 __subclass,它由 JSONModel 获取解析器并使用该值作为对象类型。 __subclass 必须是保留关键字(因此任何模型都不能使用 __subclass 作为属性名称)。
对 JSONModel.m 的更改
// ...
-(id)initWithDictionary:(NSDictionary*)dict error:(NSError**)err
{
// ...
if ([self __isJSONModelSubClass:property.type]) {
//initialize the property's model, store it
JSONModelError* initErr = nil;
-- id value = [[property.type alloc] initWithDictionary: jsonValue error:&initErr];
++ id value;
++ if([jsonValue valueForKey:@"subclass"] != NULL)
++ {
++ Class jsonSubclass = NSClassFromString([d valueForKey:@"subclass"]);
++ if(jsonSubclass)
++ obj = [[jsonSubclass alloc] initWithDictionary:d error:&initErr];
++ }
++ else
++ value = [[property.type alloc] initWithDictionary: jsonValue error:&initErr];
//...
//...
+(NSMutableArray*)arrayOfModelsFromDictionaries:(NSArray*)array error:(NSError**)err
{
// ...
for (NSDictionary* d in array) {
JSONModelError* initErr = nil;
-- id obj = [[self alloc] initWithDictionary:d error:&initErr];
++ id obj;
++ if([d valueForKey:@"subclass"] != NULL)
++ {
++ Class jsonSubclass = NSClassFromString([d valueForKey:@"subclass"]);
++ if(jsonSubclass)
++ obj = [[jsonSubclass alloc] initWithDictionary:d error:&initErr];
++ }
++ else
++ obj = [[self alloc] initWithDictionary:d error:&initErr];
// ...
// ...
注意:如果 _subclass 的 JSON 模型类不存在,则该模型将回退到父类(super class)。
这将适用于以下模型
@interface GameModel : JSONModel
@property (nonatomic, assign) long id;
@property (nonatomic, assign) NSArray<GameEventModel> *events;
@end
@protocol GameEventModel
@end
@interface GameEventModel : JSONModel
@property (nonatomic, assign) long long timestamp;
@end
@interface GameTouchEventModel : GameEventModel
@property (nonatomic, strong) NSArray *point;
@end
当传递JSON字符串时{id:1, events:[ { __subclass:'GameTouchEventModel', timestamp:1, point: [0,0] } ] }
关于ios - JSONModel iOS 和多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22159573/
这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下
我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的
1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里
print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上
我使用的是遗留数据库,所以我无法控制数据模型。他们使用了很多多态链接/连接表,就像这样createtableperson(per_ident,name,...)createtableperson_links(per_ident,obj_name,obj_r_ident)createtablereport(rep_ident,name,...)其中obj_name是表名,obj_r_ident是标识符。因此链接的报告将按如下方式插入:insertintoperson(1,...)insertintoreport(1,...)insertintoreport(2,...)insertint
有这个:classEventtrueenduser=User.create!我可以:Event.create!(:historizable=>user)但我不能:Event.where(:historizable=>user)#Mysql2::Error:Unknowncolumn'events.historizable'in'whereclause'我必须改为这样做:Event.where(:historizable_id=>user.id,:historizable_type=>user.class.name)更新重现问题的代码:https://gist.github.com/fg
当我将IO::popen与不存在的命令一起使用时,我在屏幕上打印了一条错误消息:irb>IO.popen"fakefake"#=>#irb>(irb):1:commandnotfound:fakefake有什么方法可以捕获此错误,以便我可以在脚本中进行检查? 最佳答案 是:升级到ruby1.9。如果您在1.9中运行它,则会引发Errno::ENOENT,您将能够拯救它。(编辑)这是在1.8中的一种hackish方式:error=IO.pipe$stderr.reopenerror[1]pipe=IO.popen'qwe'#
当我尝试使用“套接字”库中的方法“read_nonblock”时出现以下错误IO::EAGAINWaitReadable:Resourcetemporarilyunavailable-readwouldblock但是当我通过终端上的IRB尝试时它工作正常如何让它读取缓冲区? 最佳答案 IgetthefollowingerrorwhenItrytousethemethod"read_nonblock"fromthe"socket"library当缓冲区中的数据未准备好时,这是预期的行为。由于异常IO::EAGAINWaitReadab
我有一个UserType和一个可以是Writer或Account的userable。对于GraphQL,我想也许我可以像这样使用UserableUnion:UserableUnion=GraphQL::UnionType.definedoname"Userable"description"AccountorWriterobject"possible_types[WriterType,AccountType]end然后像这样定义我的用户类型:UserType=GraphQL::ObjectType.definedoname"User"description"Auserobject"fie
我需要将目录中的一堆文件上传到S3。由于上传所需的90%以上的时间都花在了等待http请求完成上,所以我想以某种方式同时执行其中的几个。Fibers能帮我解决这个问题吗?它们被描述为解决此类问题的一种方法,但我想不出在http调用阻塞时我可以做任何工作的任何方法。有什么方法可以在没有线程的情况下解决这个问题? 最佳答案 我没有使用1.9中的纤程,但是1.8.6中的常规线程可以解决这个问题。尝试使用队列http://ruby-doc.org/stdlib/libdoc/thread/rdoc/classes/Queue.html查看文