2010-10-27 54 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