Problem with saveToFile

2019-09-02 04:58发布

I have a problem with a NSData writeToFile. I have implemented the code below but i have an anomaly. When i run my program on the simulator, the new file is created and the informations are stored; when i build the app in my device , the file isn't created. The debug don't give me any error but don/t save anything. Can you help me? Thanks so much and sorry for my english.

-(void)saveXML:(NSString*)name:(float)x:(float)y:(float)z{

    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver setOutputFormat:NSPropertyListXMLFormat_v1_0];
    [archiver encodeFloat:x forKey:@"x"];
    [archiver encodeFloat:y forKey:@"y"];
    [archiver encodeFloat:z forKey:@"z"];
    [archiver encodeObject:name forKey:@"name"];
    [archiver finishEncoding];
    BOOL result = [data writeToFile:@"XML Position" atomically:YES];
    if(result)
        [self   updateTextView:@"success"];
    [archiver release];

}

2条回答
叛逆
2楼-- · 2019-09-02 05:39

just use NSSearchPathForDirectoriesInDomains and write your file to the path returned by this.You need not to worry about the device or simulator.

查看更多
成全新的幸福
3楼-- · 2019-09-02 05:43

You can't write to the current working directory in the iPhone because you are running in a sandbox. Also, you should check the value of result. If it is ever NO, then your write failed. Instead, you have to find the documents directory and write your files there:

-(void)saveXML:(NSString*)name:(float)x:(float)y:(float)z{

    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver setOutputFormat:NSPropertyListXMLFormat_v1_0];
    [archiver encodeFloat:x forKey:@"x"];
    [archiver encodeFloat:y forKey:@"y"];
    [archiver encodeFloat:z forKey:@"z"];
    [archiver encodeObject:name forKey:@"name"];
    [archiver finishEncoding];
    NSString* filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"XML Position"];
    BOOL result = [data writeToFile:filePath atomically:YES];
    if(result)
        [self   updateTextView:@"success"];
    [archiver release];

}
查看更多
登录 后发表回答