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
182 views
in Technique[技术] by (71.8m points)

iphone - Best way of preventing other programmers from calling -init

When designing a class hierarchy, sometimes the subclass has added a new initWithSomeNewParam method, and it would be desirable to disable calls to the old init method inherited from the superclass.

First of all, I've read the question here, where the proposed alternatives are either override init to throw an exception at runtime, or override and set default values for properties. In my case, I don't wan't to provide default values, and I want to clearly indicate that the old method should not be called, and instead the new method with parameters should be used.

So the runtime exception are fine, but unless the code is debugged, there's no way for other programmers in the team to notice that the old method is no longer intended to be used.

If I'm correct, there's no way to mark a method as "private". So, apart from adding comments, is there a way to do this?

Thanks in advance.

question from:https://stackoverflow.com/questions/9634256/best-way-of-preventing-other-programmers-from-calling-init

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

1 Reply

0 votes
by (71.8m points)

You can explicitly mark your init as being unavailable in your header file:

- (id) init __unavailable;

or:

- (id) init __attribute__((unavailable));

With the later syntax, you can even give a reason:

- (id) init __attribute__((unavailable("Must use initWithFoo: instead.")));

The compiler then issues an error (not a warning) if someone tries to call it.


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

...