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