2

我创建了另一个线程,它的功能运行良好。但唯一的情况是在新线程中我们不能使用 UIControllers。例如,我不能在新线程中使用 UIAlerview。我怎么能爱它?我尝试过的代码如下。

- (IBAction)btnCopyImage:(id)sender
{
    [NSThread detachNewThreadSelector:@selector(DownloadCheck) toTarget:self withObject:nil];

   // [self performSelectorOnMainThread:@selector(DownloadCheck) withObject:nil waitUntilDone:NO];
    NSLog(@"My name is ");
    int sum =0;
    for (int i=1; i<=1000; i++)
    {
        sum =sum+i;
    }
    NSLog(@"sum %d",sum);

}

-(void)DownloadCheck
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Download"];
    NSString* saveDialogURL = @"/Volumes/Inbox/7. Debugging and Troubleshooting.zip";
    NSString* fileNameWithExtension = saveDialogURL.lastPathComponent;

    NSLog(@"path %@ ",fileNameWithExtension);

    NSString *pathWithExtention=[NSString stringWithFormat:@"%@/%@", path,fileNameWithExtension];
    NSLog(@"path %@",pathWithExtention);

    //Remove existing file
    NSFileManager *filemgr;
    filemgr = [NSFileManager defaultManager];
    NSError *error;
    [filemgr removeItemAtPath:pathWithExtention error:&error];

    //Copy file to i phone created directory
    if ([filemgr copyItemAtPath: saveDialogURL toPath: pathWithExtention error: NULL]  == YES)
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Download"
                                                            message:@"Downloaded Sucessfully"
                                                           delegate:self
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:@"OK", nil];
        [alertView show];
        NSLog (@"Copy successful");

    }
    else
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error"
                                                            message:@"Download Faild"
                                                           delegate:self
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:@"OK", nil];
        [alertView show];
         NSLog (@"Copy Faild");
    }
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

[self performSelectorOnMainThread:@selector(DownloadCheck) withObject:nil waitUntilDone:NO];这不能使用,因为它在同一个线程上工作。

那么我应该如何使用相同的代码呢?

4

0 回答 0