0
我正在构建一个应用程序(UITabBar),我在那里存储自定义对象的NSMutableArray。我的自定义对象叫做DayModel。UITableViewController没有正确刷新
我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;
}
再现该问题:
- 甲dd item from tab nr 1
- 转到第2个标签(表格)。数据显示正确
- 转到标签页1并添加新对象
- 转到标签页2(表格)。新项目会显示来自预览项目的数据,而不是新数据。
当应用程序重新加载时,表格显示正确。
编辑
什么情况是,该新项目将在索引0加入到出现在列表的顶部,而实现代码如下类GET是从时,它应该得到它的最后一排新的信息从一开始。我怎样才能“扭转”这一点?
谢谢! Erik