[英]Can't load all of my objects for my model (NSObject) from .plist
你好。
我在我的应用中创建了模型,其中有ShoppingList和Items类(NSObject)。 每个项目只有一个ShoppingList,而ShoppingList具有更多项目
(购物清单<->>项目)
我已经将所有数据保存为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
感谢您的帮助。
NSDictionary的NSFastEnumeration实现返回键,而不是对象。 代替for (NSArray *array in loadDictionary)
您应该执行以下操作:
NSArray *itemPlist = [loadDictionary objectForKey: @"items"];
NSArray *items = [Item loadPropertyList: itemPlist];
[shoppingLists addObject: items];
但是,您可能也想使用名称和日期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.