您好。
我在我的应用程序中创建了模型,其中包含ShoppingList和Items类(NSObject)。 每个项目只有一个ShoppingList,ShoppingList有更多项目
(ShoppingList< - >>产品)
我已经将所有数据保存为plist作为NSArray和NSDictionary,但现在我有问题加载我的项目。
我的plist:
Root (NSArray)->>
___________Item 0(Dictionary)->>
________________________date(Date),name(String),items(Array)->> ____________________________________________________Item 0(Dictionary)->>
________________________________________________________________date(Date),name(String)
这是我的代码,用于编写和读取此plist:
- (NSDictionary *)propertyListRepresentation {
NSMutableArray *itemsAsPropertyLists = [NSMutableArray new];
for (Item *item in self.items) {
NSDictionary *itemPropertyList = [item propertyListRepresentation];
[itemsAsPropertyLists addObject:itemPropertyList];
}
return @{
@"name": self.nameOfList ?: @"",
@"date": self.date ?: [NSDate distantPast],
@"items": itemsAsPropertyLists,
};
}
+ (ShoppingList *)createFromPropertyListRepresentation:(NSDictionary *)plist {
ShoppingList *newList = [ShoppingList new];
newList.nameOfList = [plist objectForKey:@"name"];
newList.date = [plist objectForKey:@"date"];
return newList;
}
+ (NSArray *)loadPropertyList{
NSArray*loadData = [NSArray arrayWithContentsOfFile:@"/Users/Me/Desktop/saved.plist"];
NSMutableArray *shoppingLists = [NSMutableArray new];
for (NSDictionary *loadDictionary in loadData) {
ShoppingList *shoppingList = [ShoppingList createFromPropertyListRepresentation:loadDictionary];
[shoppingLists addObject:shoppingList];
for (NSArray *array in loadDictionary) {
NSArray *itemsArray = [NSArray new];
itemsArray = [Item loadPropertyList:array];
[shoppingLists addObject:itemsArray];
}
}
return shoppingLists;
}
对于项目:
- (NSDictionary *)propertyListRepresentation {
return @{
@"name": self.name ?: @" ",
@"date" : self.date ?:[NSDate date],
};
}
+(Item*)createFromPropertyListRepresentation:(NSDictionary*)dict {
Item *newItems = [Item new];
newItems.name = [dict objectForKey:@"name"];
newItems.date = [dict objectForKey:@"date"];
return newItems;
}
+(NSArray*)loadPropertyList:(NSArray*)array {
NSMutableArray *listOfItems = [NSMutableArray new];
for (NSDictionary*dict in array) {
Item *item = [Item createFromPropertyListRepresentation:dict];
[listOfItems addObject:item];
}
return listOfItems;
}
因此,此代码工作停止在线工作
Item *item = [Item createFromPropertyListRepresentation:dict];
错误:
-[__NSCFString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance
感谢您的帮助。
答案 0 :(得分:0)
NSDictionary的NSFastEnumeration实现返回键,而不是对象。而不是for (NSArray *array in loadDictionary)
你应该做的事情是:
NSArray *itemPlist = [loadDictionary objectForKey: @"items"];
NSArray *items = [Item loadPropertyList: itemPlist];
[shoppingLists addObject: items];
但您也可能想要对名称和日期做些什么。