Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
875 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...