문제

다음을 사용하여 수동으로 데이터 구조를 만들고있었습니다.

NSDictionary* league1 = [[NSDictionary alloc] initWithObjectsAndKeys: @"Barclays Premier League", @"name",
                 @"Premier League", @"shortname",
                 @"101", @"id", nil];
NSDictionary* league2 = [[NSDictionary alloc] initWithObjectsAndKeys: @"Coca-Cola Championship", @"name",
                 @"Championship", @"shortname",
                 @"102", @"id", nil];
NSDictionary* league3 = [[NSDictionary alloc] initWithObjectsAndKeys: @"Scottish Premier League", @"name",
                 @"SPL", @"shortname",
                 @"201", @"id", nil];
NSDictionary* league4 = [[NSDictionary alloc] initWithObjectsAndKeys: @"Champions League", @"name",
                 @"UCL", @"shortname",
                 @"501", @"id", nil];

contentArray = [[NSArray alloc] initWithObjects:

                [[NSDictionary alloc] initWithObjectsAndKeys: @"English", @"category", [[NSArray alloc] initWithObjects: league1, league2, nil], @"leagues", nil],
                [[NSDictionary alloc] initWithObjectsAndKeys: @"Scottish", @"category", [[NSArray alloc] initWithObjects: league3, nil], @"leagues", nil],
                [[NSDictionary alloc] initWithObjectsAndKeys: @"Tournaments", @"category", [[NSArray alloc] initWithObjects: league4, nil], @"leagues", nil],
                nil];

[league1 release];
[league2 release];
[league3 release];
[league4 release];

그러나 파일에서 읽은 경우 이것이 더 좋을 것이라고 생각했습니다. 그래서 나는 다음 구조를 가진 파일 Leagues.plist를 만들었습니다.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <array>
        <dict>
            <key>category</key>
            <string>English</string>
            <key>leagues</key>
            <array>
                <dict>
                    <key>name</key>
                    <string>Barclays Premier League</string>
                    <key>shortname</key>
                    <string>Premier League</string>
                    <key>id</key>
                    <string>101</string>
                </dict>
                <dict>
                    <key>name</key>
                    <string>Coca-Cola Championship</string>
                    <key>shortname</key>
                    <string>Championship</string>
                    <key>id</key>
                    <string>102</string>
                </dict>
            </array>
        </dict>
        <dict>
            <key>category</key>
            <string>Scottish</string>
            <key>leagues</key>
            <array>
                <dict>
                    <key>name</key>
                    <string>Scottish Premier League</string>
                    <key>shortname</key>
                    <string>SPL</string>
                    <key>id</key>
                    <string>201</string>
                </dict>
            </array>
        </dict>
        <dict>
            <key>category</key>
            <string>Tournaments</string>
            <key>leagues</key>
            <array>
                <dict>
                    <key>name</key>
                    <string>Champions League</string>
                    <key>shortname</key>
                    <string>UCL</string>
                    <key>id</key>
                    <string>501</string>
                </dict>
            </array>
        </dict>
    </array>
</plist>

이 파일을 어떻게 읽습니까? 다양한 방법을 시도했지만 아무것도 작동하지 않았습니다. 파일에 적합한 장소를 찾고 있는지조차 모르겠습니다. 참조를 위해 다음 방법을 시도하고 있습니다.

NSString* errorDesc = nil;
NSPropertyListFormat format;
NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"league" ofType:@"plist"];
NSData* plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
contentArray = (NSArray*)[NSPropertyListSerialization
                                     propertyListFromData:plistXML
                                     mutabilityOption:NSPropertyListMutableContainersAndLeaves
                                     format:&format
                                     errorDescription:&errorDesc];

if (!contentArray) {
    NSLog(errorDesc);
    [errorDesc release];
}

또는

NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"league" ofType:@"plist"];
contentArray = [NSArray arrayWithContentsOfFile:plistPath];

또는

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];

NSString *fooPath = [documentsPath stringByAppendingPathComponent:@"leagues.plist"];
NSLog(fooPath);
contentArray = [NSArray arrayWithContentsOfFile:fooPath];
NSLog(@"%@",contentArray);

이것은 마침내 나를 완전히 미쳤다. 도와주세요!

감사합니다

도움이 되었습니까?

해결책

NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"league" ofType:@"plist"];
contentDict = [NSDictionary dictionaryWithContentsOfFile:plistPath];

그 대답은 정확합니다 - 파일이 앱에 있다고 확신합니까? 프로젝트에 추가하고 앱 번들에 복사되는지 확인 했습니까? 그렇지 않은 경우, 파일이 구축중인 대상에 추가되지 않았을 수 있습니다. 특히 여러 대상이있는 경우 쉽게 실수합니다.

다른 팁

이 코드를 사용하십시오 plist 프로젝트의 리소스 폴더에 있습니다.

  NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"league"    ofType:@"plist"];
 contentArray = [NSArray arrayWithContentsOfFile:sourcePath];

만약 plist 앱의 문서 디렉토리 안에 있습니다.

    NSArray *paths = 
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;

NSString *plistName = @"league";
NSString *finalPath = [basePath stringByAppendingPathComponent: 
                       [NSString stringWithFormat: @"%@.plist", plistName]];



contentArray = [NSArray arrayWithContentsOfFile:finalPath];

나는이 문제를 겪었지만 Plist의 결과를 사전이되어야했던 배열에 넣었 기 때문에 작동하지 않았습니다.

NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"VehicleDetailItems" ofType:@"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];

Kendall이 맞습니다.

내 경험상 Xcode의 "Resources"폴더에 파일을 추가해야합니다.

완전성을 위해 Kendall과 Bentford는 완전히 정확합니다. 그러나 내 샘플에서 ContentArray는 속성이었고 방법이 끝날 무렵에는 범위를 벗어났습니다. arraywithContentsOffile 자동 방출 객체를 만듭니다.

이 작업을 올바르게 만들려면 세 가지 작업이 필요했습니다.

  1. 파일을 리소스 폴더에 넣습니다

  2. 파일의 이름을 올바르게 지정하십시오 (리그 대신 Leagues.Plist였습니다.

  3. 사용중인 파일을 읽으십시오 [NSARRAY ALLOC] InitWithContentsOffile : PlistPath)];

세 번째 부분은이 기능의 범위를 종료 할 때 해제되지 않는 할당 된 NSARRAY를 만듭니다. 물론, 이것은 DealLoc 함수에서 릴리스되어야했습니다.

그냥 추가하기 위해. 나는 같은 문제가 있었고 제안 된 솔루션은 문제를 해결하는 데 도움이되었지만 실제로 정확한 솔루션을 사용했는지 확실하지 않습니다. 필자의 경우 문제는 .plist 파일이 다른 대상에 추가되었다는 것입니다 (잠시 전에 새로운 대상을 추가했습니다). 따라서 솔루션은 .plist> get info> targets이며 설치할 때 장치에 복사 할 수 있도록 올바른 대상에 추가되어 있는지 확인하십시오. Darn은 내가 곧 그 사실을 알게되면 많은 시간을 절약했을 것입니다. 이것이 도움이되기를 바랍니다. 문안 인사!

파일이 리소스 폴더에 추가되지 않은 경우 문서 디렉토리에만 배치됩니다. 당신은 이것을 할 수 있습니다

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"file.plist"];
NSMutableArray *arrContentsplist = [[NSMutableArray alloc] initWithContentsOfFile:path];

이 코드가 작동합니다

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plist-name" ofType:@"plist"];
NSDictionary *Dictionary= [[NSDictionary alloc]initWithContentsOfFile:plistPath];
NSLog(@" current version CFBundleVersion = %@",[Dictionary valueForKey:@"CFBundleVersion"]);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top