I have a case where I need to modify all instances of NSView, trivial by adding a couple of lines of code to init() but how can that be done cleanly for all subclasses in Swift?
The case I have in mind:
I add a custom property to NSView via an extension
That works fine, but isn't animatable until it's registered as animatable via the layer's addAnimation:forKey: method.
So all I really need to do is ensure that addAnimation:forKey: gets called every time NSView or a subclass gets called.
Things I've considered:
Somehow doing this in an extension. Problem: extensions can't override functions, and without overriding init() or something like viewDidAppear() the code has to be called manually every time (e.g. with a convenience initialiser).
Subclass NSView and add the code. Problem: NSButton, Slider and all the rest won't inherit the code, and I have to subclass them all.
Method swizzling. This should be possible, because obj-c methods are swizzlable and NSView inherits from NSObject.
So far only swizzling seems viable, but I'm reluctant to do this because it's reliant on the APIs staying obj-c friendly, and I don't know how long that will be the case for.
Is there another way?
Related
How would I go about getting my extension to observe a property on the class it's extending while also being able to remove it at a later time?
For example:
I have a UIView, and I'd like to listen for frame changes within my UIView extension. When these changes occur I need to run some code that alters the views appearance based on the new frame.
The problem I'm having is, that while I can set up an observer, I can't figure out a way to remove it. There's no deinit() and I'd like the observer to hang around for the lifecycle of the UIView.
I'd rather not have to put this removal responsibility on the developer, and I don't want to subclass.
It doesn't even have to be KVO, if there's a better way I'd love to know about it.
The usual solution to this is to use an associated object as a deallocation spy. Associated objects are released when their attached object is deallocated, so you can run code in their deinit that you want to fire when the attached object goes away. That said, doing this really well in a multi-threaded world is a little tricky to say the least. I don't recommend building your own. Instead, I suggest PMKVObserver which will handle this for you. Even if you do choose to build your own, you should study how PMKVObserver does its magic so you're not overly naïve in your implementation.
Doing this sloppily (not worrying about multi-threaded race conditions) is not too hard in Swift, but to do it really well is better done in ObjC and bridged to Swift. Again, consult the code for the tricky corner cases.
While
Extensions can add new convenience initializers to a class, but they
cannot add new designated initializers or deinitializers to a class.
Designated initializers and deinitializers must always be provided by
the original class implementation.
So I think you cannot handle it in any nice way without subclassing.
For analytic purposes, I would like to do the following:
When a UIVIewController's viewDidLoad() is triggered, I would like to trigger a custom function vcWasLoaded(vc:UIViewController).
Similarly, when a UIButton is tapped, I would like to trigger a custom function btnWasTapped(bt:UIButton).
I would like to achieve the above without subclasses. Anyway to achieve the above using protocols, extensions, or reactive frameworks?
Method swizzling is the only thing I can think of that you could use that would let you do this without subclassing. You'd replace the implementation of viewDidLoad, and one of the lower-level button methods, and then call the original implementation in yours. (I've only dabbled in method swizzling, and it was many years ago, before Swift existed. I don't know much about Objective-C method swizzling, and know exactly zero about method swizzling in Swift.)
This would be much simpler and cleaner if you created a subclass of UIViewController and made it the base class of all of your view controllers.
I have a class that defines all styles on a UIVIew.
They are all predefined but I'm not sure when to fire this.
When I try to create an extension for this:
extension UIView
{
func willMoveToSuperview(newSuperview: UIView?)
{
self.stylize() // Another extension somewhere (not here my problem)
}
}
And I'm getting this error:
Method 'willMoveToSuperview' with Objective-C selector conflicts with
previews declaration with the same Objective-c selector
I have tried to override it, but didn't worked either.
Any ideas on how to be able to apply a same behaviour when all of my UIViews will become visible?
You can use Swizzling technic to customize UIView's function. Take a look at:
http://nshipster.com/method-swizzling/ (objective-c)
or
http://nshipster.com/swift-objc-runtime/ (swift)
Hope that helps.
Even though Swift's Extensions are similar to Categories from Objective-C, what you are trying to do is not allowed in Swift.
You cannot override existing functionality:
Extensions can add new functionality to a type, but they cannot override existing functionality.
Source: Swift Extensions - Apple Documentation
Depending on what it is that you are trying to style, you might want to take a look at UIAppearance, it will allow you to style default colors for the UINavigationBar, amongst other things. NSHipster has a good post about it: NSHipster - UIAppearance
You can create a subclass of UIView with the method .stylize().
Then each view you create, you inherit of you UIView subclass.
You'll be able to cal .stylize() on each UIViewSubclass. Simply write the style code inside the subclass and inherite.
Or
Use a category to add the method to the existing UIView class.
See : https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html
Outside of swizzling (not generally recommended), or subclassing as noted by David in his answer, there isn't really a way to override existing methods on a class and its subclasses.
One thing you might try is creating a base class for your view controller instead of all your views. In your view controller base class, you could override viewWillLayoutSubviews to recurse through the view hierarchy and call stylize on each view. This means you would be using the subclass approach in fewer places (just view controllers as opposed to all views).
Another thing you might consider if taking the subclassing approach with UIView is that if you are subclassing anyway, you can take advantage of things like #IBDesignable and #IBInspectable to better integrate those UIView subclasses with storyboards and live preview.
I wrote a Swift library which does exactly this, and it works well for the type of styling it seems you want to do: https://github.com/daniel-hall/Stylish
I am learning to program the iphone and I wanted to do some drawing. I followed some example code and subclassed the viewcontroller and it worked fine. Now as I wanted to expand the program I came upon a design question that I could use a little help on.
I subclass myviewcontroller with mynewview. If I have any code in the myviewcontroller how do I call or reference it in mynewview and vice versa? I am not sure if I am asking this right but I am trying to understand the relationship between the class and subclass.
Objective-C objects benefit from inheritance. All classes are subclasses of NSObject, therefore you can call init on any object. If you created a custom class and gave it a method doSomethingAwesome, you are free to then implement doSomethingAwesome in any subclass of your custom class. However, declaring a method in a subclass does not add that method to the superclass. As an aside, I rarely find myself subclass sing my own custom classes. I believe that it is encouraged to maintain what is called a shallow object hierarchy. Usually I subclass the stock cocoa classes, customize to my needs and if I need custom methods in more than one subclass I will declare a category on the superclass rather than relying on inheritance to provide my custom behavior
The messaging system in Objective-C is dynamic. Every object includes a struct with information that the runtime use for introspection. Here the runtime will find a list of methods the object is able to respond. So, let's say you message an instance like this:
[mynewview someMethod];
The runtime will first check the object information to trying to find some method that will be able to respond the message. If nothing is found, then will query the super class, and so on. In fact, the runtime is much more complex, and will give any object more opportunities to respond (that's the dynamic part. For instance, mynewview might not have any method called someMethod and yet, might be able to satisfy the call, but that's something you might not want to worry right now).
From a child class you can call the superclass implementation of a given method with the keyboard super, so if mynewview is a subclass of myviewcontroller you can call myviewcontroller implementation from mynewview with:
[super someMethod];
If someMethod is both present in myviewcontroller and in mynewview, the runtime will automatically only call the child implementation, you have to call the parent implementation (if you have to) from the child implementation.
I recently did a programmatic alloc/init of a table cell subclass, and with some NSLog's, I was able to learn that pretty much all of the initializers were being called even though all I did was alloc/init, if I recall correctly.
init
initWithStyle
What is the logic to this?
Which one calls which?
Everything traces back to init. A UITableViewCell is a subclass of NSObject, so it has an init method.
initWithFrame is deprecated, and has been for some time (since iOS 3). You shouldn't be using it.
It was replaced in iOS 3 with initWithStyle, which you use to indicate what style of cell you'd like to create.
initWithCoder is another NSObject method, part of the NSCoding protocol. Again, you can see it in UITableViewCell because it is a sub-class of NSObject. initWithCoder is used to unarchive an object (perhaps you have saved an object directly to a file, for example).
You can tell which calls which by looking at the order in which the log messages appear.
A common pattern in Objective-C code is to have a "designated initialiser", which actually creates and returns a configured instance of the class. All of the other initialisers call the designated initialiser with fixed values for some of the parameters that weren't specified by the caller, or provide further configuration once the designated initialiser has returned.