从plist iphone sdk获取数组中的字典对象的问题

时间:2010-05-12 07:40:58

标签: iphone plist

用于获取plist类型为字典的项目的数据类型是什么,即nsmutabledictionary或nsdictionary?因为我正在使用以下代码从plist中的字典数组中检索字典对象。

NSMutableDictionary *_myDict = [contentArray objectAtIndex:0]; //APP CRASHES HERE

NSLog(@"MYDICT : %@",_myDict);
NSString *myKey = (NSString *)[_myDict valueForKey:@"Contents"] ; 

[[cell lblFeed] setText:[NSString stringWithFormat:@"%@",myKey]];

在这里,第一行显示了objc_msgsend。 ContentArray是一个nsarray,它的内容显示了plist中的2个对象。在plist中,它们是字典对象。那为什么会出现这个错误?

编辑:

基本上,我在控制台中的contentArray的内容如下所示:

CONTENT ARRAY :  
(
    {
    favourites = 0;
    id = 0;
    story = "This is my first record";
    timestamp = 324567;
},
    {
    favourites = 0;
    id = 1;
    story = "This is my second record";
    timestamp = 321456;
}
)

我想从内容数组中检索这些字典对象。

有人可以帮忙吗?

这真的很紧急。

提前完成。

1 个答案:

答案 0 :(得分:2)

的NSDictionary。你不能简单地说

NSMutableDictionary *_myDict = [contentArray objectAtIndex:0]; 

并希望,现在它是一个可变的字典。它仍然是一个正常的不可改变的自由裁量权。所以,你应该写一些类似的东西:

NSMutableDictionary *_myDict = [NSMutableDictionary dictionaryWithDictionary:[contentArray objectAtIndex:0]];

那将从plist中的那个创建可变字典。

您可以在“Property List Programming Guide”http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Conceptual/PropertyLists/index.html

中阅读相关内容

<强>更新

你也有一个奇怪的plist内容。这里提到了可用的xml-plist类型: http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Conceptual/PropertyLists/AboutPropertyLists/AboutPropertyLists.html#//apple_ref/doc/uid/10000048i-CH3-SW1

此处描述了整体xml-plist结构: http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Conceptual/PropertyLists/UnderstandXMLPlist/UnderstandXMLPlist.html#//apple_ref/doc/uid/10000048i-CH6-SW1

工作代码

void test() {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSMutableArray *arrayIWillWrite = [NSMutableArray array];
    NSMutableDictionary *dictionary;

    dictionary = [NSMutableDictionary dictionary];
    [dictionary setObject:[NSNumber numberWithInt:0] forKey:@"favourites"];
    [dictionary setObject:[NSNumber numberWithInt:0] forKey:@"id"];
    [dictionary setObject:@"This is my first record" forKey:@"story"];
    [dictionary setObject:[NSNumber numberWithInt:324567] forKey:@"timestamp"];
    [arrayIWillWrite addObject:dictionary];

    dictionary = [NSMutableDictionary dictionary];
    [dictionary setObject:[NSNumber numberWithInt:0] forKey:@"favourites"];
    [dictionary setObject:[NSNumber numberWithInt:1] forKey:@"id"];
    [dictionary setObject:@"This is my second record" forKey:@"story"];
    [dictionary setObject:[NSNumber numberWithInt:321456] forKey:@"timestamp"];
    [arrayIWillWrite addObject:dictionary];

    [arrayIWillWrite writeToFile:@"/Users/alex/test.plist" atomically:NO];

    NSArray *arrayThatWasRead = [NSArray arrayWithContentsOfFile:@"/Users/alex/test.plist"];
    NSLog(@"%@", arrayThatWasRead);

    NSDictionary *dictionaryFromArrayThatWasRead = [arrayThatWasRead objectAtIndex:0];
    NSLog(@"%@", dictionaryFromArrayThatWasRead);

    [pool release];
}