首页 > 其他分享 >RestKit学习5:Loading Remote Objects

RestKit学习5:Loading Remote Objects

时间:2023-07-14 21:31:57浏览次数:37  
标签:Loading Remote void domestic mapping RestKit json logo

本系列的前面几篇:

RestKit学习1:引用RestKit项目
RestKit学习2:使用RestKit发送和接受请求 
RestKit学习3:CoreData 从模型到实体
RestKit学习4:Database Seeding(生成数据库文件)

这篇是从服务器的一个json接口直接获得数据,并把数据解析成对象。

需要解析的json字符串:

{"error":0,"message":"成功","list":[{"id":1,"name":"传祺","domestic":"国产","logo_ext":"jpg","logo_hash":"4081269f8b182a263b2e881e6c402a5c","seating":5},{"id":2,"name":"传祺GS5","domestic":"国产","logo_ext":"jpg","logo_hash":"b6da2a07ccd3ba7e48e0284524509a64","seating":5},{"id":3,"name":"E系列","domestic":"国产","logo_ext":null,"logo_hash":"d41d8cd98f00b204e9800998ecf8427e","seating":5},{"id":4,"name":"D系列","domestic":"进口","logo_ext":null,"logo_hash":"d41d8cd98f00b204e9800998ecf8427e","seating":3},{"id":5,"name":"V系列","domestic":"国产","logo_ext":null,"logo_hash":"d41d8cd98f00b204e9800998ecf8427e","seating":3}]}

json串对应的实体设置

注意图中的提示,一些保留字不应该出现。

RestKit学习5:Loading Remote Objects_实体类

如果中间出现错误:

“*** Assertion failure in -[RKManagedObjectMapping initWithEntity:] Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'The managedObjectClass for an object mapped entity cannot be nil.'”时,解决方法是DataModel.xcdatamodel重新生成一下实体类。

项目的引用看前面的文章。

AppDelegate.m 中Code

定义服务的地址,定义实体类跟json的映射关系

//
//  AppDelegate.m
//  testRestKit02
//
//  Created by cybercare on 12-7-30.
//  Copyright (c) 2012年
//
 
#import "AppDelegate.h"
#import <RestKit/RestKit.h>
#import <RestKit/CoreData.h>
 
#define DBNAME @"BAWSeed.sqlite"
 
 
@implementation AppDelegate
 
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary
{
    // Setup the object manager
    RKObjectManager* objectManager = [RKObjectManagerobjectManagerWithBaseURLString:@"http://www.in4s.cn:8080/Inpads/android/"];
    
    // 需要存储的文件名
    objectManager.objectStore = [RKManagedObjectStoreobjectStoreWithStoreFilename:DBNAME];
    
    // json 文件和 Core Data对象属性映射关系。
    RKManagedObjectMapping* mapping = [RKManagedObjectMappingmappingForEntityWithName:@"Series"inManagedObjectStore:objectManager.objectStore];
    
    mapping.primaryKeyAttribute = @"sid";
rootKeyPath = @"list";
    
    [mapping mapKeyPath:@"id"toAttribute:@"sid"];
    [mapping mapKeyPath:@"name"toAttribute:@"sname"];
    [mapping mapKeyPath:@"domestic"toAttribute:@"domestic"];
    [mapping mapKeyPath:@"logo_ext"toAttribute:@"logo_ext"];
    [mapping mapKeyPath:@"logo_hash"toAttribute:@"logo_hash"];
    [mapping mapKeyPath:@"seating"toAttribute:@"seating"];
    
    // Register our mappings with the provider
    [objectManager.mappingProvidersetObjectMapping:mapping forResourcePathPattern:@"/sync/series"];
    
 
    #ifdef RESTKIT_GENERATE_SEED_DB
        // 需要生成数据库时用
        // Load all the data from the file series.json into a seed database
        // The seeder will print instructions for how to copy the data to your app
    
        RKManagedObjectSeeder * seeder = [RKManagedObjectSeederobjectSeederWithObjectManager:objectManager];
    
        [seeder seedObjectsFromFile:@"series.json"withObjectMapping:mapping];
        [seeder finalizeSeedingAndExit];
    #endif
 
    returnYES;
}
 
 
- (void)applicationWillResignActive:(UIApplication
{
}
 
- (void)applicationDidEnterBackground:(UIApplication
{
}
 
- (void)applicationWillEnterForeground:(UIApplication
{
}
 
- (void)applicationDidBecomeActive:(UIApplication
{
}
 
- (void)applicationWillTerminate:(UIApplication
{
}
 
 
 
@end
 
ViewController.m 中 Code
点击一个按钮是,向服务器的服务发送请求,并获得对象实例。
 
//
//  ViewController.m
//  testRestKit02
//
//  Created by cybercare on 12-7-30.
//  Copyright (c) 2012年
//
 
#import "ViewController.h"
#import <RestKit/RestKit.h>
#import "Series.h"
 
@interfaceViewController ()
 
@end
 
@implementation
 
- (void)viewDidLoad
{
    [superviewDidLoad];
}
 
- (void)viewDidUnload
{
    [superviewDidUnload];
}
 
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
 
 
#pragma mark RKObjectLoaderDelegate methods
 
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
   
NSLog(@"4444"
    
if ([objectLoader wasSentToResourcePath:@"/sync/series"]) {
 
for(Series* item in
        {
NSLog(@"%@,%@",item.sid,item.sname);
        }
    }
}
 
- (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)error {
    UIAlertView* alert = [[UIAlertViewalloc] initWithTitle:@"Error"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:@"OK" otherButtonTitles:nil] ;
show];
    NSLog(@"Hit error: %@", error);
    NSLog(@"Rats! Failed to load objects: %@", [error localizedDescription]);
 
}
 
- (void) ButtonWasPressed:(id)sender {
    
    RKObjectManager * objectManager = [RKObjectManagersharedManager];
    
    [objectManager loadObjectsAtResourcePath:@"/sync/series"delegate:self];
}
 
 
@end

 

 

这个过程中发生了什么?

1、在 AppDelegate.m 中配置json对象跟实体类的映射关系,在AppDelegate.m中定义是为了重复利用;
2、异步向服务器发送请求 loadObjectsAtResourcePath
3、服务器返回200,以及JSON body
4、RKObjectMapper parsed payload and mapped JSON data to 实体类
5、Callback invoked with array of Contacts

 

参考资料:

https://github.com/RestKit/RestKit/wiki/Tutorial-%3A-Introduction-to-RestKit

标签:Loading,Remote,void,domestic,mapping,RestKit,json,logo
From: https://blog.51cto.com/u_15588078/6726724

相关文章

  • 若依微服务使用openfeign ,写了一个接口,但是其他项目引入的时候显示找不到这个Bean:Coul
    启动报错:org.springframework.beans.factory.UnsatisfiedDependencyException:Errorcreatingbeanwithname'tokenController':Unsatisfieddependencyexpressedthroughfield'sysLoginService';nestedexceptionisorg.springframework.beans.fa......
  • ImageMagick:报错:error while loading shared libraries: libjpeg.so.9(ImageMagick 7
    一,报错的例子:1,报错信息[root@localhostwork]#identify-listformatidentify:errorwhileloadingsharedlibraries:libjpeg.so.9:cannotopensharedobjectfile:Nosuchfileordirectory2,原因:imagemagick在调用jpeg的动态链接库时找不到相应的文件,所以报......
  • 解决远程主机的默认 shell 为 fish 时,vscode remote 无法连接的问题
    问题描述我主要用的shell就是fish,主打一个开箱即用,虽然也配置过zsh,但是感觉配置好的zsh在易用性上也就是fish的水平。此前,一直以来默认的shell都是bash,ssh或者vscoderemote远程连接上去之后,再输入fish来进行手动切换,后来嫌麻烦,就执行chsh-s/usr/bin/fish将......
  • openssl: error while loading shared libraries: libssl.so.3: cannot open shared o
    这个错误表明在加载openssl时找不到共享库文件libssl.so.3。这可能是由于缺少该共享库或者库文件路径不正确导致的。要解决这个问题,您可以尝试以下几种方法:安装OpenSSL:确保您的系统上已经正确安装了OpenSSL。您可以使用操作系统的包管理器来安装OpenSSL,具体命令可能因您......
  • 图片懒加载 loading
    loading属性设置为lazy  到今天,除了IE系列浏览器,目前都支持通过loading属性实现延迟加载。此属性可以添加到<img>元素中,也可以添加到<iframe>元素中。属性的值为loading=lazy会告诉浏览器,如果图像位于可视区时,则立即加载图像,并在用户滚动到它们附近时获取其......
  • webclient download file The remote server returned an error: (403) Forbidden,
    classWebpWebClient:WebClient{protectedoverrideWebRequestGetWebRequest(Uriaddress){HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(address);//req.UserAgent="[anywordsthatismoretha......
  • org.apache.spark.shuffle.FetchFailedException: The relative remote executor(Id:
    问题描述org.apache.spark.shuffle.FetchFailedException:Therelativeremoteexecutor(Id:21),whichmaintainstheblockdatatofetchisdead.最近在做Spark的性能优化,测试使用不同CPU核数和内存对计算性能的影响,由于是在测试集群进行测试的,硬件配置比生产上面的要少和......
  • Idea远程debug调试本地代码 Remote JVM Debug
    如果项目太大本地启动不了,或者假设你项目是微服务项目依赖太多,你写了个功能后,想本地启动debug调试又不方便,此时可以用一个idea远程debug神奇。实现访问测试环境,回调到你本地启动的代码。1,准备一个springboot项目什么都不用配置2,idea设置RemoteJVMDebug端口随便设置就行......
  • ionic LoadingController 使用cssClass改变加载样式
    以改变加载框的图表颜色和字体颜色为例在主题文件variables.scss中设置LoadingController需要改变的样式class以下使用主题颜色为加载框的图表颜色和字体颜色(当主题更改时随之改变)//加载框全局样式ion-loading.custom-loading{.loading-wrapper{--spinner-......
  • LoadingCache
    LoadingCache参数含义:1、maximumSize:设定缓存项的数目的最大值,当数目空间不足时,会使用LRU策略进行回收2、expireAfterxxx:过期逐出,例如expireAfterWrite设置为10分钟,则写入十分钟后过期4、refreshAfterWrite:例如设置为10分钟,则10分钟内没有写操作,则刷新。在到达过期时间后,对cache进......