Search code examples
objective-cnsoperationqueue

NSOperationQueue error: Thread 1: EXC_BAD_ACCESS (code = 2, address = 0x4)


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?


Solution

  • 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.