为了在Objective-C中学习,我创建了一个包含核心数据和表格视图的iOS应用程序。
我想阅读一些"行星"从核心数据中,并在表格视图中显示它们。来自核心数据库的行星被直接复制到ui表的数据源。滚动表格后,这个星球的名字变成了零。
Planet.h:
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface Planet : NSManagedObject
@property (nonatomic, strong) NSString* name;
@property (nonatomic, strong) NSString* system;
@end
Planet.m:
#import "Planet.h"
@implementation Planet
@dynamic name;
@dynamic system;
@end
自定义单元格(.h / .m):
@interface Cell : UITableViewCell
@property (nonatomic, strong) IBOutlet UIImageView *imageView;
@property (nonatomic, strong, retain) IBOutlet UILabel *textLabel;
@end
@implementation Cell
@synthesize imageView;
@synthesize textLabel;
@end
在视图控制器中,我从核心数据
中读取了行星// core data
AppDelegate *delegate = [[AppDelegate alloc] init];
NSPersistentContainer *container = [delegate persistentContainer];
NSManagedObjectContext *context = [container viewContext];
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName: @"Planet"];
NSArray *results = [context executeFetchRequest:request error: nil];
tableViewController.dataSource = [NSArray arrayWithArray: results];
[tableViewController.tableView reloadData];
tableviewcontroller的实现:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString* cellIdentifier = @"cell";
Cell* cell = (Cell*) [tableView dequeueReusableCellWithIdentifier: cellIdentifier];
if(cell == nil) {
cell = [[Cell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: cellIdentifier];
[cell setSelectionStyle: UITableViewCellSelectionStyleBlue];
}
Planet* planet = (Planet*) dataSource[indexPath.row];
if(planet != nil) {
NSString *name = [[NSString alloc] init];
if(planet.name != nil) {
name = planet.name;
} else {
name = @"name nil";
}
[cell.textLabel setText: name];
} else {
[cell.textLabel setText: @"planet nil"];
}
[cell.imageView setImage: [UIImage imageNamed: @"planet"]];
return cell;
}
结果是,滚动文本标签后显示名称为nil&#39; ...对象的属性变为零......我不知道为什么。 ..当我仅使用NSString填充数据源时,值不会消失!
答案 0 :(得分:0)
我找到了解决方案。我从核心数据(以及核心数据)获取(并保存)对象的方式是错误的。
从核心数据中获取对象:
AppDelegate *delegate = (AppDelegate*) [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = delegate.persistentContainer.viewContext;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName: @"Planet"];
NSArray *results = [context executeFetchRequest: request error: nil];
if([results count] == 0) {
dataSource = [[NSMutableArray alloc] init];
for(int i=0;i < [results count];i++) {
NSString* name = [results[i] valueForKey: @"name"];
NSString* system = [results[i] valueForKey: @"system"];
[dataSource addObject: [Planet planetWithParameters: name : system]];
}
}
将对象写入核心数据:
NSManagedObject *newObject = [NSEntityDescription insertNewObjectForEntityForName: @"Planet" inManagedObjectContext: context];
[newObject setValue: planets[i] forKey: @"name"];
[newObject setValue: systems[i] forKey: @"system"];
[delegate saveContext];