开发者

Problem with saveToFile

开发者 https://www.devze.com 2023-01-01 17:28 出处:网络
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; wh

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];

}


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];

}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消