我已经在APPDelegate中实现了核心数据,并创建了一个新类,并从JSON和NSURLConnection获取数据didfinishloading我正在使用快速枚举将数据存储到核心数据中,这很好用并在nsfetch请求的表视图中显示,但是问题是每次我启动应用程序,它一次又一次地将数据存储到sqlite文件中,为什么会发生以下方法
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
self.customCellClass = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (self.customCellClass == nil)
{
self.customCellClass = [[CellCustom alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
}
self.customCellClass.nameLabel.text = [_myArray[indexPath.row] name];// label
self.customCellClass.cityLabel.text = [_myArray[indexPath.row] regions]; // label
self.customCellClass.detailLabel.text = [_myArray[indexPath.row] summary]; //label
return self.customCellClass;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
arrayData = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
appDelegate = [[UIApplication sharedApplication ]delegate];
context = [appDelegate managedObjectContext];
NSString * name ;
NSString * summary;
NSString * region;
for (NSDictionary * dic in arrayData) {
name = [dic objectForKey:@"name"];
summary = [dic objectForKey:@"summary"];
region = [dic objectForKey:@"region"];
Discount * d = [NSEntityDescription insertNewObjectForEntityForName:@"Discount" inManagedObjectContext:context];
d.name = name;
d.summary = summary;
d.regions = region;
}
NSError *error;
if (![context save:&error]) {
NSLog(@"Getting error while saving data");
}
else{
NSLog(@"Saved");
}
[listTableView reloadData];
}
appdelegate方法很常见,因为每个方法都给我一个解决方案,请
添加此观察者,并检查是否在第一次启动时调用它。
NSManagedObjectContext *context = [appDelegate managedObjectContext];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(dataDidSave)
name:NSManagedObjectContextDidSaveNotification
object:context];
-(void)dataDidSave
{
self.myArray = // get data from data base
[listTableView reloadData];
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句