0

私は iOS 開発の新人で、以前の方法で作成した plist から値を読み取ることができません。read メソッドは (null) (null) を返します。誰が私を助けることができます?

ここで plist を作成します。

- (void)createAppPlist {

    plistPath = [self getDataFileDir];
    // Create the data structure

    rootElement = [NSMutableDictionary dictionaryWithCapacity:3];
    NSError *err;
    name = @"North America";
    country = @"United States";

    continentElement = [NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects:name, country, nil] forKeys:[NSArray arrayWithObjects:@"Name", @"Country", nil]];

    [rootElement setObject:continentElement forKey:@"Continent"];

    //Create plist file and serialize XML

    data = [NSPropertyListSerialization dataWithPropertyList:rootElement format:NSPropertyListXMLFormat_v1_0 options:0 error:&err];
    if(data)
    {
        [data writeToFile:plistPath atomically:YES];
    } else {
        NSLog(@"An error has occures %@", err);
    }

    NSLog(@"%@", rootElement);
    NSLog(@"%@", data);

}

そして、ここで値を取得しようとしています..

-(void)readAppPlist
{
    plistPath = [self getDataFileDir];
    NSMutableDictionary *propertyDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    name = [propertyDict objectForKey:@"Name"];
    country = [propertyDict objectForKey:@"Country"];

    NSLog(@"%@     %@", name, country);
}
4

1 に答える 1

1

次のコードを使用して、ドキュメント ディレクトリに Plist を作成して読み取ります。必要に応じて保存パスを変更できます。

- (void)createAppPlist {

//    plistPath = [self getDataFileDir];
    // Create the data structure

    NSMutableDictionary *rootElement = [NSMutableDictionary dictionaryWithCapacity:3];

    NSString *name = @"North America";
    NSString *country = @"United States";


    NSMutableDictionary *continentElement = [NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects:name, country, nil] forKeys:[NSArray arrayWithObjects:@"Name", @"Country", nil]];

    [rootElement setObject:continentElement forKey:@"Continent"];

    //Create plist file
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSString *filePath = [docDir stringByAppendingPathComponent:@"myPlist.plist"];
    [rootElement writeToFile:filePath atomically:YES];

    NSLog(@"%@", rootElement);
}

-(void)readAppPlist
{
    // Get pList file path
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSString *filePath = [docDir stringByAppendingPathComponent:@"myPlist.plist"];

    NSMutableDictionary *propertyDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    NSDictionary *rootDict = [propertyDict valueForKey:@"Continent"];

    // now read all elements inside, it will print key an value
    [rootDict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop){
        NSLog(@"[%@]->[%@]",key,obj);
    }];
}
于 2013-03-28T15:15:38.057 に答える