NSData initWithContentsOfFile为空

时间:2012-05-14 21:27:37

标签: iphone nsxmlparser nsdata

我创建了一个简单的测试项目来解析XML。我在我的应用程序中为此测试创建了一个.plist文件。我将它复制到documentsDirectory。我可以看到文件被复制过来了。当我尝试将其初始化为NSXMLParser的NSData对象时,我得到:

The operation couldn’t be completed. (NSXMLParserErrorDomain error 4.)

这告诉我该文件不存在。我检查过NSData不是nil,而且是fileExistsAtPath,并且都签出了确定。我有点坚持下一步尝试。有什么想法吗?感谢。

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self createEditableCopyOfDatabaseIfNeeded];

    NSString *path = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"testList.plist"];

    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
if (data == nil) {
    NSLog(@"yes nil");
}
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    parser.delegate = self;
    [parser parse];

}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void)createEditableCopyOfDatabaseIfNeeded  
{ 
    // First, test for existence. 
    BOOL success; 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSError *error; 

    NSString *writableDBPath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"testList.plist"]; 
    success = [fileManager fileExistsAtPath:writableDBPath]; 
    if (success) return; 
    // The writable database does not exist, so copy the default to the appropriate location. 
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"testList.plist"]; 
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; 
    if (!success) { 
        NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]); 
    }
}

- (NSString *)applicationDocumentsDirectory {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    return documentsDirectory;
}

#pragma mark - NSXMLParserDelegate
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
    if ([elementName isEqualToString:@"hg19Packet0.bin"]) {
        NSLog(@"first");
    }
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    NSLog(@"%@", [parseError localizedDescription]);
}

1 个答案:

答案 0 :(得分:0)

你是否从文本编辑器中查看了样本plist?如果您将其保存为二进制属性列表,则无法使用NSXMLParser进行解析(我相信)。但是,您可以使用NSPropertyListSerialization来解析它。