簡體   English   中英

如何以編程方式將文件添加到項目中

[英]how to add a file to my project programmatically

我在Application Support文件夾中創建了一個包含默認值的WinDef.plist文件。 我想將此文件添加到我的項目中,而無需手動執行。

在此輸入圖像描述

知道怎么做嗎?

羅納德

在您的應用程序中嘗試以下方法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"];

這將為您提供字典中的鍵值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM