如何以编程方式将文件添加到项目中

时间:2012-11-26 05:59:29

标签: objective-c file plist project add

我在Application Support文件夹中创建了一个包含默认值的 WinDef.plist 文件。 我想将此文件添加到我的项目中,而无需手动执行。

enter image description here

知道我该怎么做吗?

罗纳德

1 个答案:

答案 0 :(得分:2)

在您的应用程序中尝试以下方法:didfinishlaunching方法

-(void) checkAndCreateFile
    {
        //-------------------------------------------
        BOOL success;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        success = [fileManager fileExistsAtPath:cFilePath];
        //-------------------------------------------
        //File already there
        if(success)
        {
            return;
        }
        //-------------------------------------------
        //create file
        NSString *filePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:cfileName];
        [fileManager copyItemAtPath:filePathFromApp toPath:cfilePath error:nil];

    }

//------------------------------------------------------------------------
// Method : copyFile
// Method to create file
//------------------------------------------------------------------------
-(void) copyFile
{

        cfileName = @"WinDef.plist";

    NSArray *documentsPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDir = [documentsPaths objectAtIndex:0];
    cfilePath = [documentDir stringByAppendingPathComponent:cfileName];
    [self checkAndCreateFile];

}

如果您需要

,这将在您的应用程序文档文件夹中保存WinDef.plist文件

如果您想访问该文件值,则可以使用以下代码

来检索它
NSString *path = [[NSBundle mainBundle] pathForResource: @"WinDef" ofType: @"plist"]; 
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile: path];
id obj1 = [dictionary objectForKey: @"YourKey"];

这将为您提供字典中的键值