2010-10-27 58 views
1

我想通过NSThread获取-(BOOL)backupDropletUpdateAvailable返回的布尔值。NSThread - 获取布尔值

要做到这一点,我已经试过如下:

`BOOL isAvailable = NO;

[NSThread detachNewThreadSelector:@selector(backupDropletUpdateAvailable) toTarget:isAvailable withObject:nil]; 

if (isAvailable == YES) 
{//etc 

因为BOOL是整数并且是toTarget:一个指针,它返回一个警告。但是,我怎样才能获得价值?如果我不在一个单独的线程上执行此操作,那么当它出现时,我的xib将会滞后。

谢谢:)

回答

1

由线程运行的方法需要写入到该关心结果的对象将有机会获得一个位置。一种解决方案是让方法包装呼叫,获得结果,并在用户信息中发布包含结果的通知。对象可以处理通知。请注意,必须在线程启动之前创建对象,否则对象可能会错过通知。

的解决方案的草图:

#define kDropletAvailabilityNotificationName @"com.myapp.notifications.DropletAvailability" 

@implementation MyObject 
- (void)registerNotifications { 
    [[NSNotificationCenter defaultCenter] 
    addObserver:self selector:@selector(dropletAvailabilityNotification:) 
    name:kDropletAvailaibiltyNotificationName 
    object:nil]; 
} 

- (void)unregisterNotifications { 
    [[NSNotificationCenter defaultCenter] 
    removeObserver:self]; 
} 

- (void)dropletAvailabilityNotification:(NSNotification *)note { 
    NSNumber *boolNum = [note object]; 
    BOOL isAvailable = [boolNum boolValue]; 
    /* do something with isAvailable */ 
} 

- (id)init { 
    /* set up… */ 
    [self registerNotifications]; 
    return self; 
} 

- (void)dealloc { 
    [self unregisterNotifications]; 
    /* tear down… */ 
    [super dealloc]; 
} 
@end 

@implementation CheckerObject 
- (rsotine)arositen { 
    /* MyObject must be created before now! */ 
    [self performSelectorInBackground:@selector(checkDropletAvailability) withObject:nil]; 
} 

- (void)checkDropletAvailability { 
    id pool = [[NSAutoreleasePool alloc] init]; 
    BOOL isAvailable = [self backupDropletUpdateAvailable]; 
    NSNumber *boolNum = [NSNumber numberWithBool:isAvailable]; 
    [[NSNotificationCenter defaultCenter] 
    postNotificationName:kDropletAvailaibiltyNotificationName 
    object:boolNum]; 
    [pool drain]; 
} 
+0

感谢!这解决了我的问题。 – Pripyat 2010-10-27 18:38:11