0
对于Objective-C中的学习目的,我创建了一个包含核心数据和表视图的iOS应用程序。滚动后,UITableViewController中的数据源对象变为零
我想从核心数据中读取一些“行星”并在表格视图中显示它们。核心数据库中的行星被直接复制到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
在视图控制器,I读来自核心数据的行星
// 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;
}
结果是,滚动文本标签显示“名无” ...的对象变成零的性能...而且我不后不知道为什么......当我只用NSString填充数据源时,这些值不会消失!
显示dataSource'是如何'声明。 – rmaddy
声明dataSource:@property(copy,nonatomic)NSMutableArray * dataSource; – Rotzloeffel