Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
878 views
in Technique[技术] by (71.8m points)

objective c - Category conflicts

This recent question got me thinking about category conflicts, specifically involving the UIViewControllerRotation category within UIViewController.h. This category includes the shouldAutorotateToInterfaceOrientation:. If one wanted to override this method (via a category) and make it run the same code for every UIViewController (as the linked post is trying to accomplish) then they'd have two categories with the same method - something that I read leads to undefined behavior.

I gave this a try and, for a standard view-based application in iOS 4.3, the rotation logic fell back to the default, portrait only rotation, effectively ignoring the category. This was with no shouldAutorotateToInterfaceOrientation: method defined in my UIViewController subclass. Interestingly, when I did define the shouldAutorotateToInterfaceOrientation: method and simply called return [super shouldAutorotateToInterfaceOrientation:] then the category was called. So this leaves me with two question:

  1. Are all bets off (behavior-wise) when you have conflicting category methods?
  2. Is one out of luck if they wanted to override a category method w/ out inheritance?

Any feedback is much appreciated! Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Suggestion; don't do that!!!

You really don't want to override behavior of all instances of any given UIKit class across all instances within your application for a couple of reasons.

First, you'll be changing the behavior of the class in ways that the class was likely not designed to deal with. As well, instances that are in UI hierarchies that are beyond your control (embedded complex framework components, typically) will behave differently, too.

Secondly, there is no way your implementation can know the internal implementation details of the original implementation to the point of not risking failing to make the same assumptions. While you could do something swizzle-like, down that path is extremely fragile and will be a maintenance nightmare.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...