2014-10-01 44 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