将加速度计数据记录到Iphone IOS上的文件中

时间:2011-07-15 18:00:38

标签: ios accelerometer

您好我正在尝试从加速度计数据写入文件。这是我的代码:

-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {

//xax.text = [NSString stringWithFormat:@"X:[%2.6f]",acceleration.x];   
//yax.text = [NSString stringWithFormat:@"Y:[%2.6f]",acceleration.y];   
//zax.text = [NSString stringWithFormat:@"Z:[%2.6f]",acceleration.z];

NSString *acc_x = [[NSString alloc] initWithFormat:@"X:[%2.6f]",acceleration.x];
NSString *acc_y = [[NSString alloc] initWithFormat:@"Y:[%2.6f]",acceleration.y];
NSString *acc_z = [[NSString alloc] initWithFormat:@"Z:[%2.6f]",acceleration.z];

xax.text = acc_x;
yax.text = acc_y;
zax.text = acc_z;

[acc_x release];
[acc_y release];
[acc_z release];


//wfm == 2 //Initialization of Appending to the file
if (wfm == 2)
{

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSString *txtFileName = [[NSString alloc] initWithFormat:@"tmp/%@.txt",txtName.text];
    NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:txtFileName];

    //NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp/acc_w_trial2.txt"];

    //Current Contents of the file
    NSString *fileCurrent = [[NSString alloc] initWithContentsOfFile:fileName];

    //Date and Time of each Accelerometer Data
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd 'at' HH:mm:ss:SSS"];
    NSDate *date = [NSDate date];
    NSString *formattedDateString = [dateFormatter stringFromDate:date];

    NSString *msg = [[NSString alloc] initWithFormat:@"%@%@ %@%@%@ \n",fileCurrent,formattedDateString,xax.text,yax.text,zax.text];

    //Convert NSstring to NSData
    NSData* data=[msg dataUsingEncoding: [NSString defaultCStringEncoding]];

    //bool fileCreationSuccess = [fileManager createFileAtPath:fileName contents:data attributes:nil];
    [fileManager createFileAtPath:fileName contents:data attributes:nil];

    [msg release];
    [dateFormatter release];
    [fileCurrent release];
    [txtFileName release];

}   

}

我得到警告级别1和级别2.有没有办法可以释放NSFileManager内存以防止锁定?

2 个答案:

答案 0 :(得分:1)

收集加速度计数据的处理程序方法似乎效率不高。您每次都要分配资源(内存,文件),这可能需要很长时间。 您应该只分配一次所需的资源(即使用dispatch_once)并保持文件打开。使用NSFileHandle(方法fileHandleForWritingAtPath)将数据附加到文件的末尾。

此外,NSHomeDirectory()不是您应该保存用户数据的地方,因为iOS应用程序是沙盒化的。

使用NSTemporaryDirectory()或写入Documents或Library文件夹。以下是Apple的示例代码,通常在应用程序委托类中:

- (NSString *)applicationDocumentsDirectory {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}

答案 1 :(得分:0)

您可以尝试使用自动释放池。