1

我目前正在从远程服务器进行文件更新。我可以下载文件并将其保存到文档目录中。该文件有一个“Last-Modified”标签,我用它来检查文件是否需要更新。但我的问题是,如何保存带有标签的字符串以备后用?稍后我想将保存的字符串与另一个带有当前“Last-Modified”标签的字符串进行比较。如果它们相等,则不必更新文件,但如果它们不相等,我将下载新文件。

抱歉英语不好,请纠正我,感谢任何帮助。已经为此苦苦挣扎了一段时间!

编辑:

NSDictionary *metaData = [test allHeaderFields];

//NSLog(@"%@", [metaData description]);

lastModifiedString = [metaData objectForKey:@"Last-Modified"];

NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
[standardUserDefaults setObject:lastModifiedString forKey:@"LastModified"];
[standardUserDefaults synchronize];

NSString *savedString = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastModified"];

if (![lastModifiedString isEqualToString:savedString])
{
    [self downloadNewFile];
}

下载文件链接:Archive.zip

4

2 回答 2

2

使用NSUserDefaults或 Core Data 来持久化一个值。

编辑:

它不起作用,因为您在检索新值之前要保存它。你需要搬家

NSString *savedString = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastModified"];

多于

[standardUserDefaults setObject:lastModifiedString forKey:@"LastModified"];

现在,您将比较新文件值与旧用户默认值。

于 2012-01-02T17:34:33.447 回答
0

你是说你想比较最后修改的日期,看看它们是否相同?

我认为最好的方法是将日期(作为字符串)保存在Property List中。如果您正在制作一个 iPhone 应用程序,您可以使用下面的代码创建一个带有字符串的属性列表。这段代码检查一个文件是否已经存在,如果存在,它会从它读取,如果不存在,它会创建一个并写入它。

// Get the path to the property list.
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathToPlist = [[pathArray objectAtIndex:0] stringByAppendingPathComponent:@"yourfilename.plist"];
// Check whether there is a plist file that already exists.
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:pathToPlist];

if (!fileExists) { 
    // There is no file so we set the file up and save it.
    NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithCapacity:1];
    [newDict setObject:yourStringWithTheLastModifiedDate forKey:@"lastModified"];
    [newDict writeToFile:pathToPlist atomically:YES];
}

} else {
    // There is already a plist file. You could add code here to write to the file rather than read from it.
    // Check the value of lastModified.
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:pathToPlist];
    NSString *lastModifiedDate = [persistentNonResidentData objectForKey:@"lastModified"];

    // Add your own code to compare the strings.
}

或者我可能误解了你的问题,这可能不是你想要的,哈哈。

于 2012-01-02T17:44:22.690 回答