我是IOS Xcode编程的新手。目前我正在开发一个使用Json数据的应用程序。
该应用程序读取可能非常大的Json数据。我需要解析数据并将其存储到Core Data中,这样当应用程序下次运行时,它可以简单地从那里读取数据,从而节省大量时间。我尝试过使用dispatch_async
,但是在保存数据时,UI似乎被冻结,导致应用程序崩溃。
我使用ASIHTTPRequest
来读取和解析Json数据,这些数据工作得很好,但是它必须将数据保存到核心数据并同时加载到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 :(得分:0)
为您要存储的实体创建一个NSFetchedResultsController
@property (nonatomic) NSFetchedResultsController fetchedResultsController;
//Initialize it in your viewDidLoad
为NSFetchedResultsController实现委托方法
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView reloadData];
}
为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;
}
每当您持久保存一个新对象时,您的代表将被自动触发并重新加载该表,该表现在包含新对象。
修改强>
如果您想节省时间,请创建一个新的Master-Detail应用程序。在您的MasterViewController中,您将查找步骤1的源代码以及步骤3中的平滑动画。