我尝试在线程中编写一个文件,因为它在写入时会冻结我的应用程序,但是当我启动写入过程时它会崩溃
2011-10-04 21:53:51.022 xxxxxxxxx[2046:6603] *** Terminating app due to uncaught exception 'NSFileHandleOperationException', reason: '*** -[NSConcreteFileHandle seekToEndOfFile]: Operation timed out'
我的代码:
- (void)WriteTest{
[NSThread detachNewThreadSelector:@selector(DoWriteTest:) toTarget:self withObject:hFile];
}
- (void)DoWriteTest:(NSFileHandle *)aHandle{
int i;
if (aHandle) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSLog(@"---start--- writing test file --");
for (i=0; i<1024*1024; i++) {
[aHandle seekToEndOfFile];
[aHandle writeData:[NSData dataWithBytes:bytes length:(sizeof bytes) - 1]];
usleep(1);
}
NSLog(@"---end--- writing test file");
[pool release];
} else {
NSLog(@"ERROR: writing test file thread");
}
}
当我在没有线程的情况下执行此代码工作时,你能解释一下我的错误吗,我做了很多谷歌搜索,但我没有找到解决方案。感谢。
答案 0 :(得分:0)
您的代码对我有用。我的猜测是你错误地打开了文件句柄。另请注意,您应该使用[pool drain]
而不是[pool release]
,但这是挑剔。我的完整代码如下。如果您有任何疑问,请评论。希望它有所帮助。
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
fileHandle = [NSFileHandle fileHandleForWritingAtPath:@"/Users/Drew/Desktop/test.txt"];
[NSThread detachNewThreadSelector:@selector(threadSelector:) toTarget:self withObject:fileHandle];
}
- (void)threadSelector:(NSFileHandle *)aHandle {
if (aHandle) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int i;
for (i=0; i<1024; i++)
{
[aHandle seekToEndOfFile];
char buffer[1024] = "a string ";
[aHandle writeData:[NSData dataWithBytes:buffer length:(sizeof buffer) - 1]];
usleep(1);
}
[pool drain];
}
}