I've research a lot on what delegate means but somehow my understand doesn't fit with this explanation. This is from a tutorial:
physicsWorld.contactDelegate = self
and this is his explanation: "This sets up the physics world to have no gravity, and sets the scene as the delegate to be notified when two physics bodies collide."
I thought delegate is just a class that uses a protocol. Does anyone have a different explanation for this? what exactly is that line do? Thanks.
(ignore the gravity part, there's another line of code)
According to the Swift documentation for the PhysicsWorld class:
contactDelegate Property
A delegate that is called when two physics bodies come in contact with
each other.
Therefore when we see the line:
physicsWorld.contactDelegate = self
We are setting the contactDelegate property on the physicsWorld instance so that when two physics objects collide some method will be called i.e. the delegate.
By assigning self we are delegating the responsibility of responding to physics object collisions to the class (GameScene).
override func didMoveToView(view: SKView)
Because we are overriding this method in the GameScene class which inherits from the SKScene class we are essentially saying:
"Don't use SKScene didMoveToView() use this GameScene version of didMoveToView()" (because self refers to the GameScene class).
So the function "didBeginContact()" is a delegate? and contactDelegate always has to be the class that's going to implement the "didBeginContact()" function (or any other function from the delegate protocol)?
I assume that the didBeginContact() method calls the method that is set to the contactDelegate property.
Java does not have delegates. A delegate is like a variable except it stores a method. You can use the variable to then call the method. (If you know some C it is a pointer to a function)
This helped me understand delegates when I first came across them.
A delegate is a protocol, also sometimes called a "delegate protocol". The class containing the quoted line of code becomes the delegate and gets the messages of the protocol in question. The physicsWorld will contact its delegate to inform it of a collision. If the delegate methods are implemented (i.e. the controller conforms to the delegate protocol), it can take appropriate action when it is notified.
Clear?
Related
I've been working on a IOS mobile game and I wanted to take an object,duplicate it, and have the copies move all over the screen. I've looked through Google to find things relevant to this but they were all in Objective C or just didn't have what I was looking for. I want to know how to do this in Swift and SpriteKit.
If you are working with SKSpriteNode you can copy it and all it's current properties with:
let copiedNode = nodeToCopy.copy() as! SKSpriteNode
You will still need need to add copiedNode to your scene. copiedNode will also continue to run any actions that nodeToCopy was running. You can cancel them with copiedNode.removeAllActions().
Note that the documentation for the protocol NSCopying reads exactly:
Protocol
NSCopying
A protocol that objects adopt to provide functional
copies of themselves.
The exact meaning of “copy” can vary from class to class, but a copy
must be a functionally independent object with values identical to the
original at the time the copy was made...
Indeed, in the case of SKSpriteNode, Apple have interpreted that idea so that the copy() function "spawns" another instance of the item, exactly as in any game engine.
(So, for SKSpriteNode copy() works identically to the sense of Instantiate in Unity, say.)
As mogelbuster points out below, there is nowhere in the Apple documentation that they state "The spawn command in Apple is copy()" but in fact they have interpreted this "The exact meaning of “copy” can vary from class to class" in exactly that way for SKNode, since indeed it's a game engine and it's the only meaningful sense of copy there.
It's worth noting that the most completely typical way to work in games is: for your say rocketShips, you would have one "model" of your rocketShip, say modelRocketShip. The model simply sits offscreen, or is perhaps marked as invisible or inactive. You never use the model in the game, it just sits there. When you spawn rocketShips, you just dupe the model. (So in Apple that's modelRocketShip.copy() and then set the position etc.)
You can define a function to create and return a sprite :
func createSprite()->SKSpriteNode{
let sprite = SKSpriteNode(...)//Use the init function in the SKSpriteNode class
//Add some code to define the sprite's property
return sprite
}
And call this function to get some sprites that have the same property:
let spriteOne = createSprite()
let spriteTwo = createSprite()
Then you can add different SKActions to each of them so that they can behave differently.
Once you have multiple SKSpriteNodes, you can also control them by using EnumerateChildNodesWithName (assuming all your nodes have the same name) to go through all of them do do what you want in the update() function.
On a more advanced level, you could subclass SKSpriteNode and incorporate your own behaviour in your custom class.
Specifically, how does Swift memory management work with optionals using the delegate pattern?
Being accustomed to writing the delegate pattern in Objective-C, my instinct is to make the delegate weak. For example, in Objective-C:
#property (weak) id<FooDelegate> delegate;
However, doing this in Swift isn't so straight-forward.
If we have just a normal looking protocol:
protocol FooDelegate {
func doStuff()
}
We cannot declare variables of this type as weak:
weak var delegate: FooDelegate?
Produces the error:
'weak' cannot be applied to non-class type 'FooDelegate'
So we either don't use the keyword weak, which allows us to use structs and enums as delegates, or we change our protocol to the following:
protocol FooDelegate: class {
func doStuff()
}
Which allows us to use weak, but does not allow us to use structs or enums.
If I don't make my protocol a class protocol, and therefore do not use weak for my variable, I'm creating a retain cycle, correct?
Is there any imaginable reason why any protocol intended to be used as a delegate protocol shouldn't be a class protocol so that variables of this type can be weak?
I primarily ask, because in the delegation section of the Apple official documentation on Swift protocols, they provide an example of a non-class protocol and a non-weak variable used as the delegate to their class:
protocol DiceGameDelegate {
func gameDidStart(game: DiceGame)
func game(game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int)
func gameDidEnd(game: DiceGame)
}
class SnakesAndLadders: DiceGame {
let finalSquare = 25
let dice = Dice(sides: 6, generator: LinearCongruentialGenerator())
var square = 0
var board: [Int]
init() {
board = [Int](count: finalSquare + 1, repeatedValue: 0)
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
}
var delegate: DiceGameDelegate?
func play() {
square = 0
delegate?.gameDidStart(self)
gameLoop: while square != finalSquare {
let diceRoll = dice.roll()
delegate?.game(self, didStartNewTurnWithDiceRoll: diceRoll)
switch square + diceRoll {
case finalSquare:
break gameLoop
case let newSquare where newSquare > finalSquare:
continue gameLoop
default:
square += diceRoll
square += board[square]
}
}
delegate?.gameDidEnd(self)
}
}
Should we take this as a hint that Apple thinks we should be using structs as delegates? Or is this simply a bad example, and realistically, delegate protocols should be declared as class-only protocols so that the delegated object can hold a weak reference to its delegate?
Should we take this as a hint that Apple thinks we should be using structs as delegates? Or is this simply a bad example, and realistically, delegate protocols should be declared as class-only protocols so that the delegated object can hold a weak reference to its delegate?
Here's the thing. In real life Cocoa programming, the delegate is likely to be an existing class. It is a class because it exists for some other purpose that only a class can satisfy - because Cocoa demands it.
For example, very often, to take iOS as an example, one view controller needs to act as another view controller's delegate for purposes of arranging a message back and forth between them. Ownership of the view controllers is dictated by the view controller hierarchy and by nothing else. So, in Swift, just as in Objective-C, you had better make that delegate property weak, because it would be terrible if one view controller suddenly took memory management ownership of another view controller!
So, in the real world of the Cocoa framework, there is serious danger of incorrect ownership or of a retain cycle. And that is the problem that weak solves. But it only works, as you rightly say, with classes.
The example in the book, however, is about some objects living off in an abstract made-up artificial Swift-only world. In that world, as long as you aren't in danger of circularity (retain cycle), there's no reason not to use structs and there's no reason to worry about memory management. But that world is not the world you will usually be programming in! And that world is not the framework Cocoa world that your Objective-C delegate pattern comes from and belongs to.
Yes, this example is a bit of an oddity.
Because the example uses a non-class protocol type, it has to expect a possible struct implementing the protocol, which means that the DiceGame instance owns its delegate. And indeed, that violates typical assumptions about the delegate pattern.
It doesn't lead to a reference cycle in this case because the DiceGameTracker is a fictional object that doesn't own the DiceGame itself — but in a real-world app it's possible, even likely, that a delegate might also be the owner of the delegating object. (For example, a view controller might own the DiceGame, and implement DiceGameDelegate so it can update its UI in response to game events.)
That kind of reference cycle would probably turn into a confusing mess if either the game, its delegate, or the type implementing one or both of those protocols were a value type — because value types are copied, some of the variables in your setup would end up being distinct copies of the game (or game's owner).
Realistically one would expect to use reference types (classes) to implement this anyway, even if the protocol declaration leaves open the possibility of doing it otherwise. Even in a hypothetical Swift-only world, it probably makes sense to do it that way... generally whenever you have something with long life, internal mutable state, and a usage pattern that has it being accessed by potentially multiple other actors, you want a class type, even if you can sort of fake otherwise with value types and var.
If you must have structs and emums in your protocol, then if you make your delegate nil just before you close the view controller, then this breaks the retain cycle. I verified this in Allocations in Instruments.
// view controller about to close
objectCreatedByMe.delegate = nil
It's an optional, so this is valid.
I'm creating a ViewController object an pushing it to a navigation controller.
When the object is being popped from the stack - it is not being release and Deinit is not being called. What can be the reason for that?
Here's the code that pushes:
self.navigationController?.pushViewController(CustomViewController(), animated: true)
And here's the code that pops:
self.navigationController?.popViewControllerAnimated(true)
I had similar problem. I added empty deinit method to my class and added breakpoint:
deinit {
}
As result it's never called.
As soon as I add some code to the body it started working as expected:
deinit {
print("deinit called")
}
So be sure that your deinit method isn't empty.
PS. I am using Swift 2, Xcode 7.1
Do any of your classes, or properties they contain make a reference to the view controller you've popped?
If your UIViewController has created an instance of an object, which in turn makes a 'strong' reference to that view controller (e.g. a reference that's not explicitly declared 'weak' or 'unowned'), and your view controller keeps a strong reference to that object as well, neither will be deallocated. That's called a strong reference cycle, documented here (a must read for serious Swift developers):
The Swift Programming Language (Swift 3.0.1): Automatic Reference Counting
Closures are a more insidious case where you can get into trouble.
One thing you might try as an experiment is pushing the controller and popping it before you do anything in viewDidLoad or in the initialization, and see if the deinit method is being called. If it is, then you should be able to incrementally discover what you're doing that's leading to the symptom you're seeing.
Another thing that can thwart diagnosis (as other answers have pointed out), which I learned the hard way, is that the debugger breakpoint won't be taken for deinit() if the deinit method contains no executable statements, because the OS or compiler optimizes the deinit invocation away if it's empty, so at least put a print statement there if you want to verify deinit() is getting called.
I was using this tutorial Custom TabBar with a custom seque on the given page. The memory problem was due a subview which had a strong reference the the parent viewcontroller.
class WBMNewsFeedV: UIView
{
var parentVC:WBMHomeTabVC!
}
WBMNewsFeedV - subclass
parentVC:WBMHomeTabVC - parent class ViewController
I changed it to :
class WBMNewsFeedV: UIView
{
weak var parentVC:WBMHomeTabVC!
}
So, the strong reference was nested inside a subviews and not visible at first. Hope this helps anyone. After the change deinit was always called in
WBMHomeTabVC
I had the same issue when the NotificationCenter was holding a strong reference to the presented view controlled and thus it was never getting released. So I had to add [weak self] to the block like this:
(in the viewDidLoad)
NotificationCenter.default.addObserver(forName: .showFoo, object: nil,
queue: OperationQueue.main) { [weak self] (notification) in
if let foo = notification.userInfo?["foo"] as? Foo {
self?.afooButton!.setImage(UIImage(named: "foo"), for: .normal)
}
}
add some line code of in deinit. If You put breakpoint at Empty deinit ,compiler will not stop you there
put this:
deinit {
print("any thing")
}
It will work ;)
I had a timer in my view controller, running every minute to update a label. I put a call in deinit to invalidate the timer, which I'm pretty sure is what I've always done in Objective-C (in dealloc) and it's worked. But it seems a little different in Swift so I moved the time creation/invalidation code to viewWillAppear/viewWillDisappear (which makes more sense really) and everything seems fine now!
I just ran into a similar issue. My problem appears to have been caused by a strong reference to a control that had delegate assignment not specified as 'weak' with a class type protocol.
I had same issue what I found is I didn't make weak reference for my other class delegate
protocol SomeClassDelegate : AnyObject {
func someClassDelegateMethod(<param>)
}
class SomeClass: NSObject {
// Make delegate weak reference
weak var delegate:InfractionDataManagerDelegate? = nil
< some code >
}
now deinit is being called on my implementation class.
Just to add an edge case which I found very difficult to detect:
If you allocate any UnsafeMutablePointers and provide self (the UIViewController) as pointee inside of your view controller, make sure to call pointer.deinitialize(count:), not just pointer.deallocate().
Otherwise, the reference to self will remain and the UIViewController will not deinitialize.
I faced the same Problem. In my case a never ending cycle of UIView.animateWithDuration... holds the ViewController in Memory and blocks the call of deinit. If you use something like this you have to stop it first bevor you remove the ViewController. Hope that helps.
I had a similar issue: I had some UIViews as arranged subviews of a *stackview" contained in a scrollview in a detail view controller. It worked when I removed the UIViews from the stackview on back button tap (willMove(toParent parent: UIViewController?)). Another thing to check is when in your view controller you have something like: let session = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue()) (that self could in some cases prevent a detail view controller to be deallocated when you click Back and move to the master)
First of all make sure to define deinit
deinit {
print("OverlayView deinit")
}
Use Xcode's object graph to check number of instances being created and if they are not getting deallocated then they will keep growing.
I was creating property of another ViewController on top of the file so i move it and place it in the scope it was being used that solved my problem. And its deinit started calling.
Moreover i was using a uiview property to show a overlay that need to be accessed from my viewcontroller at some places i make it optional and set it nil when after calling removefromsuperview on it.
var overlay: OverlayView?
overlay = nil
If still dealloc not calling then there could be a retain cycle issue as described above in that case you will have to check another viewcontroller(B) too if its calling back this controller(A) then set one of them as a weak variable.
the most helping material that I could find in this problem is link
But for me the problem was typealias
I've defined two classes in an m file, the first subclassing UIView and the second UIViewController. The UIViewController is instantiated at some point, and the vc is who instantiates my first class.
the first class implements the touchesEnded method, to simulate a button. when the touchesEnded method is fired in the first class, is it possible to easily call a method defined in the 2nd class, without going into delegates and such?
I tried playing with selectors with no luck
is it possible to easily call a method defined in the 2nd class
Yes, assuming that you are creating an instance of the second class and calling the method on that instance.
Regardless of whether the two classes are subclasses of the same type, or in the same or different files, you need a reference to an instance of that class to call a method on it, or force it to perform a selector.
The proper OO way to do this is with delegates, but you could theoretically do something like pass a reference to view 2 into view 1 when you create the views. If you create them in IB you could create outlets so they reference each other that way.
In short: Yes, it is possible and easy to do, but I can't give you too much in terms of specific code without a more specific example of your situation
what is the exact meaning of delegate in iphone?how it is implemented in UIViewController?
A delegate is an object that usually reacts to some event in another object and/or can affect how another object behaves. The objects work together for the greater good of completing a task. Typically a delegate object will be shared by many other objects that have a more specific task to carry out. The delegate itself will be more abstract and should be very reusable for different tasks. The object which contains the delegate typically sends the delegate a message when a triggered event occurs, giving the delegate an opportunity to carry out its specified task.
There's more documentation here that you should read to understand the delegate pattern in Cocoa and Cocoa touch, particularly with how delegation is used between UIWindow and UIView. It is an integral design pattern in iPhone architecture and one that should be mastered if you wish to design a clean application.
Delegates are used to delegate tasks of objects to their owner (or any object, really). A good reason for this is it makes it easier to use composition instead of inheritance. Delegates are a reference to an object that conform to a specified protocol so you can guarantee it will implement the required methods. A good example is UIApplicationDelegate. Notice how the delegated methods (from the protocol) use verbs that applicationDid, applicationShould, applicationWill etc. Usually delegate methods either ask for permission to do something (and choose to do it this way, in a method, rather than with just a BOOL property, for more flexibility) or notify the delegate of an event that will happen or did happen.
Delegation is a pattern and the term means the same in Cocoa.
A delegate is not implemented in a UIViewController. Different kinds of view controllers are assigned a delegate to handle certain tasks. One of the best examples (if we're talking iPhone) is the UITableViewDelegate, which is called to do certain things when certain table-related events occur.
A delegate is used to communicate/pass data b/w two objects of a class/struct to complete a task.
For example: Consider firstVC(sender or Delegator or CEO) which sends confidential data to secondVC(receiver or Delegate or Secretary).
This is done by making secondVC conforming to a
protocol passDataDelegate { func passdata(data: String) }
class secondVC : UIViewController, passDataDelegate {
func passdata(data: String) {
print("CEO passed //(data)")
}
}
class firstVC : UIViewController {
var delegate : passDataDelegate?
}
Now create objects of both firstVC & secondVC
let sender = firstVC()
let receiver = secondVC()
Since, receiver conforms to protocol passDataDelegate. So, it is having type either as UIViewController or passDataDelegate because if a class conforms to a protocol then the object of its class can have protocol as type.
Hence, assign sender.delegate = receiver
Now, we can CEO(sender) can pass data to Secretary(receiver) through its delegate property as
sender.delegate?.passdata("Confidential data")
Output: CEO passed Confidential data
Now the Secretary(receiver) can use that data to complete her further task.
The concept of delegation is very common in iOS. An object will often rely on another object to help it out with certain tasks. This separation of concerns keeps the system simple as each object does only what it is good at and lets other objects take care of the rest. The table view offers a great example of this.