pasawaya
pasawaya

Reputation: 11595

Is there any method called directly after drawRect:?

I have two UIView subclasses, say "Class A" and "Class B". Class A, in its initializer, has the code [self addSubview:instanceOfClassB];. And in Class B's drawRect: is the line of code [self addSubview:imageViewInstance];. Also in Class B's drawRect: I assign values to that imageView instance's animationImages, animationDuration, and animationRepeatCount properties. However, I also call startAnimating on this UIImageView instance, but it always crashes the application. I then tried calling startAnimating on that UIImageView instance from the drawRect: of Class B's superview, Class A. However, it still crashes with the error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[__NSArrayM insertObject:atIndex:]: object cannot be nil'

And has the "Thread 1: signal SIGABRT" message on the line with the code [imageView startAnimating];.

I suspect that it is crashing here because the drawRect of Class B is being called after the drawRect of Class A, so when I tell the image view to start animating it crashes because the image view has not been created yet. So basically what I'm asking is in what method can I tell the image view to start animating without a crash?

Upvotes: 1

Views: 468

Answers (1)

Thomas Zoechling
Thomas Zoechling

Reputation: 34253

Modifying state or calling methods unrelated to drawing from within drawRect: sounds like a very bad idea - You shouldn't do anything in drawRect: except drawing.

drawRect: is automatically called whenever a view or a portion of a view needs re-redrawing. The frequency and the order of redrawing operations is determined by the system and depends on several things (view hierarchy, occlusion, ...) - So you also can't rely on a specific order in which drawRect: gets called.

You could move the setup of your objects out of your drawing code and start the animations based on user interaction.

Upvotes: 2

Related Questions