2014-10-01 97 views
-3

我使用ASIHTTPRequest解析数据。现在,我想将这个 数据存储在核心数据中。使用this API。 我的实体名称短信,包括三个ID,名称和IsActive。 此代码解析数据。如何在核心数据中添加JSON解析数据?

-(void)DataRetireve 
{ 
    deatilinfoarray = [[NSMutableArray alloc] init]; 
    NSURL *url = [NSURL URLWithString: 
    @"http://sms.instatalkcommunications.com/apireq/GetSMSCategories? 
    t=1&h=admin&param=1"]; 
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];`` 
    [request setDelegate:self]; 
    [request startAsynchronous]; 
} 

- (void)requestFinished:(ASIHTTPRequest *)request 
{ 

    NSError *error; 

    NSString *responseString = nil; 

    if (!error) 
    { 
     responseString = [request responseString]; 

     SBJsonParser *parser = [[SBJsonParser alloc] init] ; 

     NSMutableArray *jsondata = [parser objectWithString:responseString]; 
     NSMutableArray *jsondata1 = [[NSMutableArray alloc]init]; 
     info *myinfo=[[info alloc]init]; 
     for(int i=0;i<jsondata.count;i++) 
     { 

      [email protected]"Id"; 
      [email protected]"Name"; 
      [email protected]"IsActive"; 

      [jsondata1 addObject:myinfo]; 
      NSLog(@"%@",responseString); 

     } 
      for(int i=0;i<jsondata1.count;i++) 
      { 
      myinfo= [jsondata1 objectAtIndex:i]; 

       NSManagedObjectContext *context=[self managedObjectContext]; 
       NSManagedObject *sms = [NSEntityDescription insertNewObjectForEntityForName:@"SMS" inManagedObjectContext:context]; 


       NSLog(@"%@", context); 

       [sms setValue:@"Id" forKey:@"Id"]; 
       [sms setValue:@"Name" forKey:@"Name"]; 
       [sms setValue:@"IsActive" forKey:@"IsActive"]; 

       [jsondata1 addObject:myinfo]; 

      } 

完成代码这一点,但给我的错误

+0

当然,用这行代码NSManagedObjectContext * context;您没有有效的托管对象上下文。从AppDelegate获取权限或将其传递给您的相关ViewController。 – Matz 2014-10-02 07:18:21

+0

我通过这段代码 - (NSManagedObjectContext *)managedObjectContext { NSManagedObjectContext * context = nil; id delegate = [[UIApplication sharedApplication] delegate]; if([delegate performSelector:@selector(managedObjectContext)]) { context = [delegate managedObjectContext]; } return context; } – 2014-10-02 08:03:18

+0

给我看这个错误int main(int argc,char * argv []){ @autoreleasepool { return UIApplicationMain(argc,argv,nil,NSStringFromClass([AppDelegate class])); } } – 2014-10-02 08:05:56

回答

1

首先,我认为ASIHTTPRequest是一种过时的。根据original site最后修改于2011年。我建议您切换到http://afnetworking.com/

现在,关于JSON到核心数据。首先,你应该使用NSJSONSerialization解析JSON数据。你可以看看这个问题(How to use NSJSONSerialization)了解更多信息。

然后,你的实体创建一个新的NSManagedObject:

NSManagedObject *aSMS = [NSEntityDescription insertNewObjectForEntityForName:@"SMS" 
                 inManagedObjectContext:context]; 

然后就是设置的值。像:

aSMS.Name = JSON[@"Name"]; 
+0

我完成了所有代码,但它给了我错误 – 2014-10-02 07:03:12

+0

您收到了哪个错误? – LuisEspinoza 2014-10-02 12:51:09

+0

没有错误,但我混淆了数据库中添加的数据 – 2014-10-03 05:56:19