我正在尋找建議/如何創建一個逗號分隔的日誌文件在iPhone上的實現當我的數據以相對較快的速度(每次200次第二)。我期望捕獲每個數據點的時間戳和2-3個整數。在15分鐘內,會有15 * 60 * 200 = 180,000行數據,每個數據都有一個時間戳,一些整數和一個換行符。iOS iPhone尋找快速記錄時間戳整數數據文件執行
我想確保將這些數據寫入磁盤的順序是正確的。
我目前的實施已針對每秒鐘以1個數據點進入的數據進行了優化,對於「快速」數據可能效率不高。 如何調整我的代碼以確保它可以在後臺線程中運行,而不會爲每次寫入佔用太多資源?另外,是否有一個快速的「登錄到數據文件」的實現,我可以給它一個數字並在稍後要求它提供一個日誌文件?
NSString *appDataFile ;
NSFileHandle *aFileHandle;
-(NSString*)dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
appDataFile = [documentsDirectory stringByAppendingPathComponent:@"Data"];
aFileHandle = [NSFileHandle fileHandleForWritingAtPath:appDataFile];
return appDataFile;
}
//creates a new log file for each app run, or appends to existing log
-(void)writeStringToDataFile:(NSString *)csvLine
{
if(aFileHandle)
{
//telling aFilehandle what file write to
[aFileHandle truncateFileAtOffset:[aFileHandle seekToEndOfFile]]; //setting aFileHandle to write at the end of the file
[aFileHandle writeData:[csvLine dataUsingEncoding:NSUTF8StringEncoding]];
}else{
NSData* headers = [@"timestamp,waveform amplitude,score, connection, event\n" dataUsingEncoding:NSUTF8StringEncoding];
//clear the old log file
NSError *error = nil;
NSFileManager* fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:[self dataFilePath] error:&error];
//create CSV headers
aFileHandle = [NSFileHandle fileHandleForWritingAtPath:appDataFile];
[headers writeToFile:appDataFile atomically:YES];
aFileHandle = [NSFileHandle fileHandleForWritingAtPath:appDataFile];
//telling aFilehandle what file write to
[aFileHandle truncateFileAtOffset:[aFileHandle seekToEndOfFile]]; //setting aFileHandle to write at the end of the file
[aFileHandle writeData:[csvLine dataUsingEncoding:NSUTF8StringEncoding]];
}
}
怎麼樣:用NSArray將數據存儲在內存中。然後使用後臺線程繼續從NSArray檢索數據,並將其寫入文件。這將很容易實施和維護?你可以創建一個先進先出隊列,這樣你就不會用完內存 – vodkhang 2013-03-10 01:25:58
謝謝你的建議。我目前有一個〜600個數據點的循環數組,用於以1 /秒進入的數據,並且每2分鐘使用數組索引實現自動保存數據的自動保存。使用普通數組需要太多內存(在快速記錄的情況下高達21 Mb) – 2013-03-11 14:34:17