Multi-Threading question in Objective-C 2.0

前端 未结 3 1924
Happy的楠姐
Happy的楠姐 2021-02-11 05:35

I have my main application delegate which contains a method that returns an object. This application delegate runs on the main thread.

I also have a NSOperation that get

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-11 06:25

    Do you absolutely need to perform this invocation on the NSOperation thread, and not simply provide the required object as part of creating the custom operation?

    If so, I would recommend not using locks unless performance is critical. If the iPhone supported it, you could use Grand Central Dispatch to get the object onto your thread:

    __block id newObject = nil;
    dispatch_sync(dispatch_get_main_queue(), ^{
        newObject = [[[[UIApplication sharedApplication] delegate] myMethod] retain];
    });
    

    For the iPhone, I would be tempted to create a helper method:

    - (void)createNewObject:(NSValue *)returnPtr {
        id newObject = [[[[UIApplication sharedApplication] delegate] myMethod] retain];
        *(id *)[returnPtr pointerValue] = newObject;
    }
    

    And invoke it like so from your NSOperation thread:

    id newObject = nil;
    [self performSelectorOnMainThread:@selector(createNewObject:)
                           withObject:[NSValue valueWithPointer:&newObject]
                        waitUntilDone:YES];
    

    Actually performing the execution on the main thread has fewer implicit risks.

提交回复
热议问题