在 NSThread 崩溃应用程序中使用 NSFileHandle 写入文件
我尝试在线程中写入一个文件,因为它在写入时冻结了我的应用程序,但是当我启动写入过程时,它使
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");
}
}
当我在没有线程的情况下执行此操作时,此代码可以工作,你能解释一下我错了什么吗,我让很多谷歌搜索但我没有找到解决方案。谢谢。
I attempt to write a file in thread because it freeze my app when writing but when i launch writing process it crash
2011-10-04 21:53:51.022 xxxxxxxxx[2046:6603] *** Terminating app due to uncaught exception 'NSFileHandleOperationException', reason: '*** -[NSConcreteFileHandle seekToEndOfFile]: Operation timed out'
my code:
- (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");
}
}
when i did this without a thread this code work, can you explain me what i'm wrong please, i make a lot of google search but i don't find a solution. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的代码对我有用。我的猜测是您错误地打开了文件句柄。另请注意,您应该使用
[pool排出]
而不是[poolrelease]
,但这是挑剔的。我的完整代码如下。如果您有任何疑问,请评论。希望有帮助。Your code worked for me. My guess is you opened your file handle incorrectly. Also note that you should use
[pool drain]
instead of[pool release]
, but this is nitpicking. My full code is below. Comment if you have any questions. Hope it helps.