You'll need to use an atomic operation to access tempSum in the main thread as well and make sure tempSum is on a 4 byte boundary (required by atomic ops).

But a cleaner method would be to keep a local running total in the worker thread and after your time period send a message to the main thread with the worker total as an NSNumber for the object for performSelectorOnMainThread... Then the main thread adds this value to the full total. The basic idea would look like:


//Worker thread
- (void)add2Number: (int)i
{
static int localSum = 0; //Don't use static if you're running this same method from multiple threads.
                                                  //But from a single worker 
it's ok and convenient

        localSum += i;

        if ( more than 0.1 seconds have passed )
        {
[ self performSelectorOnMainThread:@selector(addToSum:) withObject: [NSNumber numberWithInt:localSum] waitUntilDone:NO];

                localSum  = 0;  //reset local sum for next round
        }
}


//Main thread
- (void)addToSum:(NSNumber*)num
{
        sumTotal += [num intValue];     

        self.sum = sumTotal;
}

This avoids the complexities of managing atomic reads/writes.

On Mar 15, 2009, at 11:43 PM, Gerriet M. Denkmann wrote:

Could you please point to the exact section where it is stated that it is not OK to update a bound property from a background thread?


If main is an instance of the Main class, which has:

- (void)add2Number: (int)i
{
        OSAtomicAdd32 (i, &tempSum);

        if ( more than 0.1 seconds have passed )
[ self performSelectorOnMainThread:@selector(reallySum) withObject:nil waitUntilDone:NO];
}

- (void)reallySum
{
        self.sum = tempSum;
}

The property "sum" is bound to the "value" of some NSTextField.

Is is ok to send [ main add2Number: someNumber ] from another thread?

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to