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