2013-03-25 39 views
1

我是IOS Xcode編程的新手。目前我正在研究使用Json數據的應用程序。 該應用程序讀取的Json數據可能非常大。我需要解析數據並將其存儲到核心數據中,以便下次運行應用程序時,只需從該處讀取數據即可節省大量時間。我嘗試過使用dispatch_async,但UI似乎被凍結,同時數據被保存也導致應用程序崩潰。 我使用ASIHTTPRequest來讀取和解析Json數據,這些數據工作的很好,但是它必須將數據保存到核心數據並同時將其加載到UITableView中,這被證明是痛苦的。 如果有人能幫助我,我將非常感激。將Json數據保存到coredata IOS並同時在UITableView中顯示

這裏是我的代碼

NSString *connectionString = [NSString stringWithFormat:@"%@%@?song_id=%@", SERVER_STRING, URL_GET_SONG_LIST, lasSongID]; 

NSLog(@"COnnection String is:\n%@", connectionString); 
NSURL* url = [NSURL URLWithString:connectionString]; 

//The actual request 
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 

// Becoming the request delegate 
//To get callbacks like requestFinished: or requestFailed: 
[request setDelegate:self]; 
NSLog(@"Fetching Dataaaaaaaa from %@",url); 

// Fire off the request 
[request startAsynchronous]; 

-(void) requestFinished: (ASIHTTPRequest *) request 
{ 
    NSString *theJSON = [request responseString]; 
    NSLog(@"Dataaaaaaaa,%@",theJSON); 
    NSDictionary *responseDictionary = [theJSON JSONValue]; 

    if ([[responseDictionary valueForKey:@"Message"] isKindOfClass:[NSArray class]]) 
    { 
     [songsArray addObjectsFromArray:[responseDictionary valueForKey:@"Message"]]; 

     if (songsArray.count > 0) 
     { 
      dispatch_async (bgQueue, ^(void){ 
       [self saveDownloadedSongs];    
      }); 
     } 
    } 
} 

saveDownloadedSongs - 一些驗證後>保存JSON來我的核心數據

回答

0
  1. 對於要存儲

    @property (nonatomic) NSFetchedResultsController fetchedResultsController; 
    //Initialize it in your viewDidLoad 
    
    你的實體創建一個NSFetchedResultsController
  2. 你的視圖控制器應該是你的NSFetchedResultsControllerDelegate
  3. 爲NSFetchedResultsController

    實現委託方法
    - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller 
    { 
        [self.tableView reloadData]; 
    } 
    
  4. 實現您的數據源方法的UITableView

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
    { 
        return self.fetchedResultsController.sections.count; 
    } 
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
    { 
        return [self.fetchedResultsController.sections[0] numberOfObjects]; 
    } 
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    { 
        static NSString *CellIdentifier = @"Cell"; 
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 
    
        if (cell == nil) { 
         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
        } 
    
        SomeObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath]; 
        cell.label.text = object.property 
        return cell; 
    } 
    
  5. 每次你堅持你的代表將被觸發自動一個新的對象,並重新加載表,現在包括新的對象。

編輯:

如果你想節省時間,創建一個新的主從應用。在您的MasterViewController中,您將查找步驟1的源代碼和步驟3中的流暢動畫。

相關問題