I would like to inherit from a framework class that has a factory method. How can I make the factory method return an object of my inherited class type? I found this useful article which describe a similar situation but in their case you have control over the superclass. How could I write, say, a subclass of UIImage
that imageNamed:
would return an object of my subclass type?
相关问题
- how to define constructor for Python's new Nam
- Keeping track of variable instances
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- Core Data lightweight migration crashes after App
相关文章
- 现在使用swift开发ios应用好还是swift?
- 接口B继承接口A,但是又不添加新的方法。这样有什么意义吗?
- Could I create “Call” button in HTML 5 IPhone appl
- TCC __TCCAccessRequest_block_invoke
- xcode 4 garbage collection removed?
- Unable to process app at this time due to a genera
- How can I add media attachments to my push notific
- How do you detect key up / key down events from a
The approach that solved my problem was to use a category instead of inheritance (credits go to Jonathan Cichon in the comments of my question). I used Associative References to declare and store additional data in the category implementation as discussed a lot here in SO. I would like to drive the attention to the
NSObject
category implementation proposed by Jonathan that makes really easy and elegant to add associative references to any object.This is all you should have to do:
Then:
+[UIImage imageNamed:]
's implementation wrote subclassers out of this approach. Consequently, you would need to implement this method yourself.Here's how one should declare a factory method:
and how one should implement it:
but they did not do it that way --
+[UIImage imageNamed:]
wrote subclasses out and returns aUIImage
when you writeMONImage * img = [MONImage imageNamed:pName];
. Sometimes that is done for a good reason. Some methods should have 'final' semantics. This often appears when your method may return multiple types, as in a class cluster. The language does not express 'final' methods -- but such a method should at least be documented.So to come around to this
UIImage
case:Note that
UIImage
s andCGImage
s are immutable. This should not result result in a deep copy of the image data.For your example:
UIImage
to, say,MyImage
imageNamed:
method to do anything specific that you need to be done.MyImage *newImage = [MyImage imageNamed:imageName];