views:

88

answers:

2

Hi, 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  A: 

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

}
Jason Coco
Totally agree. That's what zp26 need.
Jim
and where i store it in my iphone?
zp26
A: 

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

anurag
i can try these but i don't find the file.Don't find in my pc and in my iPhone.
zp26
use NSLog(@"zp26 %@",filePath);just after the line NSString *filePath=.......you can see the path of the file in your pc
anurag
i think zp26 ,by now you would have succedded in finding the file in your pc???All the very best
anurag