从项目中提取NSDictionary

时间:2015-02-18 14:06:51

标签: ios objective-c

我在一个项目中有NSDictionary随着时间的推移而创建,我需要将该项目中的所有数据从这个项目中转移到另一个项目中。

任何想法如何在不逐一添加的情况下实现它?

我考虑过将所有东西都提取到数组中并传递数组,但它并不是一个很好的选择

2 个答案:

答案 0 :(得分:4)

Probaly不是最好的解决方案,但它会正常工作。

您可以使用以下步骤将字典转换为字符串。 然后记录字符串并复制它。之后,您可以在新项目中执行相反的步骤。

项目1

NSDictionary *dictionary = [NSDictionary alloc]init];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:&error];
NSString *dictionaryString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@",dictionaryString); #Copy this string from the debugger

项目2

NSError *error;
NSString *dictionaryString = @"PASTE_DEBUGGER_STRING";
NSData *jsonData = [dictionaryString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

答案 1 :(得分:0)

我会将其写入文件,然后将其导入新应用中。首先,您将在应用程序中运行该方法,然后从iTunes中的documents文件夹中获取该文件。将其添加到新应用程序的documents文件夹中,然后添加阅读代码。

保存:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *stringsPlistPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"myDictionary.plist"];

BOOL success = [myDictionary writeToFile:stringsPlistPath atomically:YES];

if (success) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Your configuration file is in the Documents folder of the app which is accessible via iTunes." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
} else {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"There was a problem creating the configuration file. Please try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
}

阅读:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *stringsPlistPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"myDictionary.plist"];

NSDictionary *loadedDictionary = [NSDictionary dictionaryWithContentsOfFile:stringsPlistPath];

这会将您的文件保留在那里。如果你想删除它:

NSFileManager *fileManager = [NSFileManager defaultManager];

NSError *error;
BOOL success = [fileManager removeItemAtPath:stringsPlistPath error:&error];

if (success) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"The configuration file was successfully loaded and has now been removed." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
}
else
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"The configuration file was successfully loaded but could not be removed. You will need to remove it manually." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
}