【发布时间】:2017-10-08 09:17:02
【问题描述】:
出于学习 Objective-C 的目的,我创建了一个带有核心数据和表格视图的 iOS 应用程序。
我想从核心数据中读取一些“行星”并在表格视图中显示它们。核心数据数据库中的行星被直接复制到 ui 表的数据源中。在表格中滚动后,行星的名称变为 nil。
行星.h:
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface Planet : NSManagedObject
@property (nonatomic, strong) NSString* name;
@property (nonatomic, strong) NSString* system;
@end
行星.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 读取行星
// 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;
}
结果是,滚动文本标签后显示'name nil'......对象的属性变成了nil......我不知道为什么......当我只用NSString填充数据源时,价值观不会消失!
【问题讨论】:
-
显示
dataSource的声明方式。 -
数据源声明:@property (copy, nonatomic) NSMutableArray *dataSource;
标签: objective-c uitableview properties null