开发者

writing file with NSFileHandle in NSThread crash app

I attempt to write a file in thread because it 开发者_StackOverflow中文版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.


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.

- (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];
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜