-1

我尝试在线程中写入文件,因为它在写入时冻结了我的应用程序,但是当我启动写入过程时它崩溃了

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");
    }
}

当我在没有线程的情况下执行此代码时,请您解释一下我错了什么,我进行了很多谷歌搜索,但找不到解决方案。谢谢。

4

1 回答 1

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];
    }
}
于 2011-10-04T20:50:13.117 回答