Pergunta

Eu estava criando uma estrutura de dados manualmente usando o seguinte:

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];

No entanto, eu pensei que isso seria melhor se fosse lido em um arquivo. Então, eu criei as ligas de arquivo.plist, que tem a seguinte estrutura:

<?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>

Como faço para ler esse arquivo. Eu tentei vários métodos, mas nada funcionou. Eu nem sei se estou procurando no lugar certo para o arquivo. Para referência, estou tentando os seguintes métodos:

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];
}

ou

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

ou

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);

Isso finalmente está me deixando completamente insano. Ajuda por favor!

Obrigado gentilmente

Foi útil?

Solução

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

Essa resposta está correta - você tem certeza de que seu arquivo está no aplicativo? Você o adicionou ao seu projeto e verificou se ele é copiado em seu pacote de aplicativos? Caso contrário, pode ser que o arquivo não tenha sido adicionado ao destino que você está construindo, um erro fácil de cometer, especialmente se você tiver vários alvos.

Outras dicas

Use este código se o plist está na pasta de recursos do projeto.

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

Se o plist está dentro do diretório de documentos do aplicativo, use isto:

    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];

Eu tive esse problema, mas não estava funcionando porque estava colocando os resultados da plata em uma matriz onde deveria ter sido um dicionário, ou seja,

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

Kendall está correto.

Na minha experiência, você precisa adicionar seu arquivo à pasta "Recursos" no Xcode.

Para completude, Kendall e Bentford estão completamente corretos. No entanto, na minha amostra, o contentArray era uma propriedade e, no final do método, estava saindo do escopo porque ArraywithContentsOffile cria um objeto lançado automaticamente.

Para fazer isso funcionar corretamente, eu precisava fazer 3 coisas:

  1. Coloque o arquivo na pasta de recursos

  2. Nomeie o arquivo corretamente (era ligas.plist em vez de liga.plist)

  3. Leia o arquivo usando [NSARRAY ALLOC] initWithContentsOffile: PlistPath)];

A terceira parte cria um NSARRAY alocado que não é lançado quando você sai do escopo dessa função ... é claro, isso precisava ser lançado na função Dealloc.

Just to add. I had the same problem and the suggested solution helped me solve the problem, however I am not sure if I actually used the exact solution. In my case the problem was that the .plist file was added to a different target (had added a new target a moment before). Therefore the solution was .plist > Get Info > Targets, and make sure it is added to the correct target so it gets copied to device when installing. Darn had I figure that out soon enough I would have saved a lot of time. Hope this is helpful too. Regards!

If the file is not added in the resources folder and only placed in your documents directory. You can do this

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

This Code is working

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plist-name" ofType:@"plist"];
NSDictionary *Dictionary= [[NSDictionary alloc]initWithContentsOfFile:plistPath];
NSLog(@" current version CFBundleVersion = %@",[Dictionary valueForKey:@"CFBundleVersion"]);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top