EzDevInfo.com

delegates interview questions

Top delegates frequently asked interview questions

How can I make a weak protocol reference in 'pure' Swift (w/o @objc)

weak references don't seem to work in Swift unless a protocol is declared as @objc, which I don't want in a pure Swift app.

This code gives a compile error (weak cannot be applied to non-class type MyClassDelegate):

class MyClass {
  weak var delegate: MyClassDelegate?
}

protocol MyClassDelegate {
}

I need to prefix the protocol with @objc, then it works.

Question: What is the 'pure' Swift way to accomplish a weak delegate?


Source: (StackOverflow)

What are the differences between delegates and events?

What are the differences between delegates and an events? Don't both hold references to functions that can be executed?


Source: (StackOverflow)

Advertisements

What's the best way to communicate between view controllers?

Being new to objective-c, cocoa, and iPhone dev in general, I have a strong desire to get the most out of the language and the frameworks.

One of the resources I'm using is Stanford's CS193P class notes that they have left on the web. It includes lecture notes, assignments and sample code, and since the course was given by Apple dev's, I definitely consider it to be "from the horse's mouth".

Class Website:
http://www.stanford.edu/class/cs193p/cgi-bin/index.php

Lecture 08 is related to an assignment to build a UINavigationController based app that has multiple UIViewControllers pushed onto the UINavigationController stack. That's how the UINavigationController works. That's logical. However, there are some stern warnings in the slide about communicating between your UIViewControllers.

I'm going to quote from this serious of slides:
http://cs193p.stanford.edu/downloads/08-NavigationTabBarControllers.pdf

Page 16/51:

How Not To Share Data

  • Global Variables or singletons
    • This includes your application delegate
  • Direct dependencies make your code less reusable
    • And more difficult to debug & test

Ok. I'm down with that. Don't blindly toss all your methods that will be used for communicating between the viewcontroller into your app delegate and reference the viewcontroller instances in the app delegate methods. Fair 'nuff.

A bit further on, we get this slide telling us what we should do.

Page 18/51:

Best Practices for Data Flow

  • Figure out exactly what needs to be communicated
  • Define input parameters for your view controller
  • For communicating back up the hierarchy, use loose coupling
    • Define a generic interface for observers (like delegation)

This slide is then followed by what appears to be a place holder slide where the lecturer then apparently demonstrates the best practices using an example with the UIImagePickerController. I wish the videos were available! :(

Ok, so... I'm afraid my objc-fu is not so strong. I'm also a bit confused by the final line in the above quote. I've been doing my fair share of googling about this and I found what appears to be a decent article talking about the various methods of Observing/Notification techniques:
http://cocoawithlove.com/2008/06/five-approaches-to-listening-observing.html

Method #5 even indicates delegates as an method! Except.... objects can only set one delegate at a time. So when I have multiple viewcontroller communication, what am I to do?

Ok, that's the set up gang. I know I can easily do my communication methods in the app delegate by reference's the multiple viewcontroller instances in my appdelegate but I want to do this sort of thing the right way.

Please help me "do the right thing" by answering the following questions:

  1. When I am trying to push a new viewcontroller on the UINavigationController stack, who should be doing this push. Which class/file in my code is the correct place?
  2. When I want to affect some piece of data (value of an iVar) in one of my UIViewControllers when I am in a different UIViewController, what is the "right" way to do this?
  3. Give that we can only have one delegate set at a time in an object, what would the implementation look like for when the lecturer says "Define a generic interface for observers (like delegation)". A pseudocode example would be awfully helpful here if possible.

Source: (StackOverflow)

Why must a lambda expression be cast when supplied as a plain Delegate parameter

Take the method System.Windows.Forms.Control.Invoke(Delegate method)

Why does this give a compile time error:

string str = "woop";
Invoke(() => this.Text = str);
// Error: Cannot convert lambda expression to type 'System.Delegate'
// because it is not a delegate type

Yet this works fine:

string str = "woop";
Invoke((Action)(() => this.Text = str));

When the method expects a plain Delegate?


Source: (StackOverflow)

How can I clear event subscriptions in C#?

Take the following C# class:

c1 {
 event EventHandler someEvent;
}

If there are a lot of subscriptions to c1's someEvent event and I want to clear them all, what is the best way to achieve this? Also consider that subscriptions to this event could be/are lambdas/anonymous delegates.

Currently my solution is to add a ResetSubscriptions() method to c1 that sets someEvent to null. I don't know if this has any unseen consequences.


Source: (StackOverflow)

How do I create delegates in Objective-C?

I know how delegates work, and I know how I can use them.

But how do I create them?


Source: (StackOverflow)

Why would you use Expression> rather than Func?

I understand lambdas and the Func and Action delegates. But expressions stump me. In what circumstances would you use an Expression<Func<T>> rather than a plain old Func<T>?


Source: (StackOverflow)

Why are Objective-C delegates usually given the property assign instead of retain?

I'm surfing through the wonderful blog maintained by Scott Stevenson, and I'm trying to understand a fundamental Objective-C concept of assigning delegates the 'assign' property vs 'retain'. Note, the both are the same in a garbage collected environment. I'm mostly concerned with a non-GC based environment (eg: iPhone).

Directly from Scott's blog:

"The assign keyword will generate a setter which assigns the value to the instance variable directly, rather than copying or retaining it. This is best for primitive types like NSInteger and CGFloat, or objects you don't directly own, such as delegates."

What does it mean that you don't directly own the delegate object? I typically retain my delegates, because if I don't want them to go away into the abyss, retain will take care of that for me. I usually abstract UITableViewController away from its respective dataSource and delegate also. I also retain that particular object. I want to make sure it never goes away so my UITableView always has its delegate around.

Can someone further explain where/why I'm wrong, so I can understand this common paradigm in Objective-C 2.0 programming of using the assign property on delegates instead of retain?

Thanks!


Source: (StackOverflow)

Using delegates in C#

I'm new here and I'm also new in C# language and .NET framework. Could you help me with understanding delegates? I was trying to check some code, and found that the results I received were unexpected for me. Here it is:

class Program
{
    public static int I = 0;

    static Func<string> del = new Func<string>(I.ToString);

    static void Main(string[] args)
    {
        I = 10;
        Console.WriteLine("{0}", del());
    }
}

The answer was 0, but not 10. Why? Thank you and I'm sorry about my poor English.


Source: (StackOverflow)

Function Pointers in Java

This may be something common and trivial, but I seem to be having trouble finding a concrete answer. In C# there is a concept of delegates, which relates strongly to the idea of function pointers from C++. Is there a similar functionality in Java? Given that pointers are somewhat absent, what is the best way about this? And to be clear, we're talking first class here.


Source: (StackOverflow)

What is Delegate? [closed]

I am confused that what is the actual role of a delegate? I have been asked this question many times in my interviews, but I don't think that interviewers were satisfied with my answer.

Can anyone tell me the best definition, in one sentence, with a practical example ?

Thanks


Source: (StackOverflow)

Wrapping StopWatch timing with a delegate or lambda?

I'm writing code like this, doing a little quick and dirty timing:

var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000; i++)
{
    b = DoStuff(s);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);

Surely there's a way to call this bit of timing code as a fancy-schmancy .NET 3.0 lambda rather than (God forbid) cutting and pasting it a few times and replacing the DoStuff(s) with DoSomethingElse(s)?

I know it can be done as a Delegate but I'm wondering about the lambda way.


Source: (StackOverflow)

How do I set up a simple delegate to communicate between two view controllers?

I have two UITableViewControllers and need to pass the value from the child view controller to the parent using a delegate. I know what delegates are and just wanted to see a simple to follow example.

Thank You


Source: (StackOverflow)

Func vs. Action vs. Predicate [duplicate]

This question already has an answer here:

With real examples and their use, can someone please help me understand:

  1. When do we need Func delegate?
  2. When do we need Action delegate?
  3. When do we need Predicates delegate?

Source: (StackOverflow)