我正在从文本文件中填充TableView。我想让用户下载更新的文本文件,并将TableView的现有内容替换为下载文件的内容。我可以下载文件并替换原始文件。如果我关闭应用程序并再次打开它,它会加载更新的文件。
但是,当应用程序运行时,TableView不会更改。当我执行方法将数据从文件加载到TableView时,我可以看到,使用NSLog,该方法从文件中获取原始数据。
我做错了什么?如何让方法查看更新的文本文件而不是原始文本文件?
感谢。
@interface
@property (strong, nonatomic) NSArray *tableViewData;
@end
@implementation
/*
When user presses button, IBAction method
- downloads text file
- saves the downloaded file, replacing the original text file
- loads the text file into the TableView data (this is what doesn't work)
- sends a reload message to the TableView
*/
- (IBAction)buttonUpdateTextFile:(UIBarButtonItem *)sender
{
NSString *contentsOfTextFile = [self downloadTextFileFromURL:@"http://www.apple.com/index.html"];
[self saveContentsOfTextFile:contentsOfTextFile toFile:@"tableViewData.txt"];
[self loadDataFromFileWithFileName:@"tableViewData" fileExtension:@"txt"];
[self.tableView reloadData];
}
- (NSString *)downloadTextFileFromURL:(NSString *)textFileURLstring
{
NSURL *textFileURL = [NSURL URLWithString:textFileURLstring];
NSError *error = nil;
NSString *contentsOfTextFile = [NSString stringWithContentsOfURL:textFileURL encoding:NSUTF8StringEncoding error:&error];
return contentsOfTextFile;
}
- (void)saveContentsOfTextFile:(NSString *)contentsOfTextFile toFile:(NSString *)fileName
{
NSString *pathName = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileNameWithPath = [pathName stringByAppendingPathComponent:fileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileNameWithPath]) {
[[NSFileManager defaultManager] createFileAtPath:fileNameWithPath contents:nil attributes:nil];
[[contentsOfTextFile dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileNameWithPath atomically:NO];
}
- (void)loadDataFromFileWithFileName:(NSString *)fileName fileExtension:(NSString *)fileExtension
{
NSString *path = [[NSBundle mainBundle] pathForResource:fileName
ofType:fileExtension];
NSString *content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSString *remainingText = [content mutableCopy];
NSMutableArray *data = [[NSMutableArray alloc] init];
NSRange *substringRange;
while (![remainingText isEqualToString:@""]) {
substringRange = [remainingText rangeOfString:@"/n"];
if (substringRange.location == NSNotFound)
{
currentLine = remainingText;
remainingText = @"";
} else {
substringRange.length = substringRange.location;
substringRange.location = 0;
currentLine = [[remainingText substringWithRange:substringRange] mutableCopy];
// - strip line from remainingText
substringRange.location = substringRange.length + 1;
substringRange.length = remainingText.length - substringRange.length - 1;
remainingText = [[remainingText substringWithRange:substringRange] mutableCopy];
}
[data addObject:currentLine];
}
self.tableViewData = [data copy];
}
答案 0 :(得分:0)
我认为
self.tableViewData = [data copy];
可能是问题。
我会将数据设为"私有"班级的财产。只有init一次,然后手动添加和删除对象。不要使用副本。