0
我在做什麼:解析XML以創建NSManagedObject子類並始終解析失敗。Objective-C將XML解析爲NSManagedObjects
代碼在這裏:
NSData* data = [[NSString stringWithUTF8String:answerString.c_str()] dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser *nsXmlParser = [[NSXMLParser alloc] initWithData:data];
XMLParser *parser = [[XMLParser alloc] initXMLParser];
[nsXmlParser setDelegate:parser];
BOOL success = [nsXmlParser parse];
其中answerString
是std::string
。而且我總是在success
旗下獲得NO
。
我的對象類:
@interface System : NSManagedObject
@property (nonatomic, retain) NSString * systemFullName;
@property (nonatomic, retain) NSString * systemShortName;
@end
我的解析器頭:
@class System;
@interface XMLParser : NSObject <NSXMLParserDelegate>
{
NSMutableString *currentElementValue;
System *system;
}
- (XMLParser *) initXMLParser;
與實現
- (XMLParser *) initXMLParser
{
self = [super init];
return self;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:@"System"])
{
system = [NSEntityDescription insertNewObjectForEntityForName:@"System"
inManagedObjectContext:((AppDelegate*)[[UIApplication sharedApplication]
delegate]).managedObjectContext];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if (!currentElementValue)
{
currentElementValue = [[NSMutableString alloc] initWithString:string];
} else
{
[currentElementValue appendString:string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
NSManagedObjectContext *context = ((AppDelegate*)[[UIApplication sharedApplication]
delegate]).managedObjectContext;
if ([elementName isEqualToString:@"System"])
{
[context save:nil];
system = nil;
}
if ([elementName isEqualToString:@"systemFullName"])
{
system.systemFullName = currentElementValue;
}
if ([elementName isEqualToString:@"systemShortName"])
{
system.systemShortName = currentElementValue;
}
}
任何想法?
我偶然發現,當方法didEndElement
查找第一個對象的結束,只是XMLParser的停止工作,錯誤111
解析時出現了什麼錯誤? – Leena