【发布时间】:2014-12-07 12:58:27
【问题描述】:
我正在构建一个应用程序 (UITabBar),我在其中存储自定义对象的 NSMutableArray。我的自定义对象名为 DayModel。
我的 DayModel.h 文件:
#import <Foundation/Foundation.h>
@interface DayModel : NSObject
@property (nonatomic, retain) NSDate *mydate;
@property (nonatomic) float myFloat;
@end
我的 DayModel.m 文件:
#import "DayModel.h"
@implementation DayModel
@synthesize myDate, myFloat;
-(id)init {
// Init self
self = [super init];
if (self) {
// Setup
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder;
{
[coder encodeObject:self.myDate forKey:@"myDate"];
[coder encodeObject:self.myFloat forKey:@"myFloat"];
}
- (id)initWithCoder:(NSCoder *)coder;
{
self = [[DayModel alloc] init];
if (self != nil)
{
self.myDate = [coder decodeObjectForKey:@"myDate"];
self.myFloat = [coder decodeFloatForKey:@"myFloat"];
}
return self;
}
@end
“主”视图控制器,保存新对象:
// Add data to the DayModel class
DayModel *currentDay = [[DayModel alloc] init];
currentDay.myDate = myDate;
currentDay.myFloat = myFloat;
// Add currentDay to the _objects NSMutableArray
[_objects insertObject:currentDay atIndex:0];
// Save this array using NSKeyedArchiver
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:_objects] forKey:@"objects"];
我的 UITableViewController 显示这个:
viewWillAppear
// Load the _objects array
NSData *objectsData = [defaults objectForKey:@"objects"];
if (objectsData != nil)
{
NSArray *oldArray = [NSKeyedUnarchiver unarchiveObjectWithData:objectsData];
if (oldArray != nil)
{
_objects = [[NSMutableArray alloc] initWithArray:oldArray];
} else
{
_objects = [[NSMutableArray alloc] init];
}
} else
{
_objects = [[NSMutableArray alloc] init];
}
其他方法:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [_objects count];
}
加载数据:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
// Get the DayModel
DayModel *currentModel = [[DayModel alloc] init];
currentModel = _objects[indexPath.row];
// Get the UILabels
UILabel *dateLabel = (UILabel *)[cell viewWithTag:10];
UILabel *floatLabel = (UILabel *)[cell viewWithTag:20];
// Create the DateFormatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
// Set the text
dateLabel.text = [dateFormatter stringFromDate:currentModel.myDate];
floatLabel.text = [NSString stringWithFormat:@"%.02f", currentModel.myFloat];
return cell;
}
重现问题:
- 从标签 nr 1 添加项目
- 转到标签 nr 2(表格)。数据显示正确
- 转到标签 nr 1 并添加新对象
- 转到标签 nr 2(表格)。新项目与预览项目中的数据一起显示,而不是新数据。
重新加载应用时,表格会正确显示。
编辑
发生的情况是新项目被添加到索引 0 以显示在列表的顶部,而 tableview 类从最后一行获取新信息,而它应该从顶部获取它。我怎样才能“扭转”这个?
谢谢! 埃里克
【问题讨论】:
标签: ios objective-c uitableview object nsmutablearray