Question

I like to create an NSOperationQueue, the NSOperatioQueue should refresh a UILable, I created this code:

NSOperationQueue * ramQueue = [NSOperationQueue alloc];
    [ramQueue addOperationWithBlock:^{
        while (TRUE) {

            //Creating String

            NSOperationQueue *main = [NSOperationQueue mainQueue];
            [main addOperationWithBlock:^{

                //Refresh Label

            }];

        }

    }];

But it wont work, the label isnt showing the new strings. is is showing an error here: [ramQueue addOperationWithBlock:^{

Anyone know how to fix this?

Was it helpful?

Solution 2

A couple of thoughts:

  1. That [NSOperationQueue alloc] should be [[NSOperationQueue alloc] init].

  2. I'd generally advise against a never ending while loop. If you want to repeatedly do something, a repeating timer (at some reasonable rate, probably not more than 10-20 times per second) might be a better construct. If you use the while loop construct, you could easily end up posting operations to the main queue faster than the main loop can process them. (It depends upon what's inside that while loop.)

  3. If you stay with that while loop (which, again, I'd discourage you from doing), you probably want an @autoreleasepool inside there so any auto released objects get deallocated.

    [ramQueue addOperationWithBlock:^{
        while (TRUE) {
            @autoreleasepool {
                //Creating String
    
                NSOperationQueue *main = [NSOperationQueue mainQueue];
                [main addOperationWithBlock:^{
    
                    //Refresh Label
                }];
            }
        }
    }];
    

    You might even want to use semaphores to ensure the background operation doesn't post events too quickly.

  4. Probably unrelated to your problem, but if you're doing anything that is updating any shared resources (e.g. changing any class properties or ivars), make sure to synchronize those with the main queue. You can do that by dispatching those updates back to the main queue or employ some locking mechanism.

OTHER TIPS

OK, I wanna thank Rob, for pointing me in the right direction!

here is my right code:

First of all I created [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(updateRam) userInfo:nil repeats:YES]; instead of the while(TRUE){} loop. then I corrected my NSOperationQueue code like this:

-(void)updateRam {

    NSOperationQueue * ramQueue = [[NSOperationQueue alloc] init];
    [ramQueue addOperationWithBlock:^{

        //Create String

        NSOperationQueue *main = [NSOperationQueue mainQueue];
        [main addOperationWithBlock:^{

         //Refresh Label

        }];

    }];
}

Thanks agan!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top