Menu
  • HOME
  • TAGS

Passing information to a custom TableViewCell - Swift

uitableview,swift,delegates,datasource,tableviewcell

So your custom TableViewCell should have it's own class (for example ImageTableViewCell) which takes care of the image you will set when loading the TableView: @IBOutlet var titleLabel: UILabel! @IBOutlet var imageView: UIImageView! and in the TableView: override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell =...

Swift delegation - when to use weak pointer on delegate

swift,delegates,weak-references

You generally make class protocols (as defined with class keyword) weak to avoid the risk of a "strong reference cycle" (formerly known as a "retain cycle"). Failure to make the delegate weak doesn't mean that you inherently have a strong reference cycle, but merely that you could have one. With...

How to send enum type to Invoke (delegate) Visual C++

visual-c++,enums,delegates

As documented by MSDN Control::Invoke Method (Delegate, array) the Invoke method accepts these parameters: method Type: System::Delegate A delegate to a method that takes parameters of the same number and type that >are contained in the args parameter. args Type: array An array of objects to pass as arguments to...

Does the order of the delegate functions matter in iOS?

ios,objective-c,ios8,delegates

No order doesn't matter.. The function called based on Event/State of application not based on written order..

Calling a Method on an Objective-C Delegate from Swift

ios,objective-c,swift,delegates,protocols

When Swift examines the property delegate it simply sees that is is an NSObject and the fact that you have noted that it implements a protocol is ignored. I can't find any specific documentation as to why this is the case. You can address this in a couple of ways....

Passing string back in popViewControllerAnimated

ios,uitableview,delegates,didselectrowatindexpath

A few things: remove id myDelegate; inside your @interface ViewController2 change your @property (nonatomic, assign) id... to @property (nonatomic, weak) id..., that is just safer (see why) Regarding your question: you present the view via a segue!? Therefore you need to overwrite the prepareForSegue method, extract the destinationViewController from the...

Xcode, have delegate method auto-include classes

ios,xcode,autocomplete,delegates

All of the methods in the UITextFieldDelegate protocol are optional, so Xcode won't give you any warnings. If you try something like UITableViewDataSource, you'll see Xcode gives you warnings for the required methods that your class hasn't implemented. I don't know of a way to auto-fill those methods, but it's...

Delegate with generic list signature for passing data to another form

c#,winforms,events,delegates

If you want to use event handlers, you should follow the general pattern, defining a class that inherits EventArgs (supposing you want to involve a list in the event) in this way: // Event Args public class ProfileImportEventArgs : EventArgs { private IList<string> list; public ProfileImportEventArgs(IList<string> list) { this.list =...

c# function which has method parameter value, or using delegate

c#,delegates,delegation

Pass a delegate, like this: // CHANGE HERE public void GenericFunction(Action action) { frmLoadingControl _frmLoadingControl = new frmLoadingControl(); _frmLoadingControl.Show(this); BackgroundWorker _BackgroundWorker = new BackgroundWorker(); _BackgroundWorker.DoWork += (s, args) => { this.Invoke(new MethodInvoker(() => this.Enabled = false)); // CHANGE HERE action(); Execute(_FunctionCode); }; _BackgroundWorker.RunWorkerCompleted += (s, args) => { _frmLoadingControl.Close(); this.Invoke(new...

Why is a delegated method public when declared in a private section?

ruby-on-rails,ruby,delegates,metaprogramming

Yes, the issue is with module_eval because it explicitly sets public visibility before evaling passed string. It behaves in the same way in CRuby and JRuby. For example, incriminated code for CRuby is in eval_under function. As you've figured out, when you pass def_delegate to private method it becomes private....

Variable losing value in delegation pattern

objective-c,delegates

Change this line: @property (nonatomic, assign) id delegate; to: @property (nonatomic, weak) id <Class1Delegate> delegate; assign should only be used for C primitives, not Objective-c object references. You should also be checking if your object actually conforms to the delegate before messaging the delegate. Edit: I think you may be...

Setting delegates (for protocols) only works in prepareForSegue?

ios,objective-c,delegates,protocols

When instantiated from a storyboard, the initWithCoder: methid is called, not the init method. DestinationViewController *destinationVC = [[destinationViewController alloc] init]; destinationVC.delegate = self; is how you do when your controller is not from a storyboard: you init it from the code. After that you have to manually handle the transition...

UISearchController & UISearchBar Subclass

ios,objective-c,delegates,uisearchbar,uisearchcontroller

It looks like you are setting the search bar's delegate to be your instance of VLSearchController. However that class does not conform to the UISearchBarDelegate protocol. I believe you want to set _searchBar.delegate = _searchBar where you have implemented your delegate methods. There can only be one delegate for the...

Event syntax vs delegate syntax in c# application

c#,.net,events,syntax,delegates

even in my code I can access to the event from outside the class and raise it No, you can't. You could call p.OnChange() since OnChange is a simple property, but you can not call pubevent.OnchangeEvent() since OnchangeEvent is an event. The compiler would complain with The event 'UserQuery.PubEvent.OnchangeEvent'...

Swift - Passing data along with segues

ios,swift,uiviewcontroller,delegates,segue

You are currently calling sendName and sendImage delegates before assigning them any value . Thats why they are not getting to your InformationViewController. You should do something like that: override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "newReciep" { var vc = segue.destinationViewController as! DetailsViewController vc.delegateDetails = self...

swift method accept parameter if conform a protocol

ios,swift,delegates

Update You are trying to reference an instance in a type method. Instead of this, WebService.executeRequest(self, url: "", postParameters: params, headerParameters: params) write this: WebService.executeRequest(Authentication.self, url: "", postParameters: params, headerParameters: params) Then later in for example Authentication: class Authentication: NSObject, WebServiceProtocol { // ... func someMethod() { WebService.executeRequest(self, url: "",...

Setting the delegate from third to first viewController

ios,objective-c,delegates,protocols

You'd have to pass along the A controller through to the B controller to be set as the delegate for C when it is created. Kind of messy. In this case though it might make more sense to use a notification model where Controller A listens for a NSNotification that...

Subclass as delegate of superclass

ios,objective-c,inheritance,uiviewcontroller,delegates

You should declare your protocol as @protocol ImageViewControllerDelegate <NSObject> This says that any object that conforms to your protocol will also conform to the NSObject protocol that respondsToSelector: is declared in....

Reflection - Add a Delegate to another Delegate's invocation list

c#,reflection,delegates

This seems to work... There are various comments inside... I'm not sure if this is the best way to do it. I'm building an Expression tree to do the delegate invocation. public static void AddHandler(this object obj, Action action) { var events = obj.GetEvents(); foreach (var @event in events) {...

Passing variable arguments to a delegate

c#,.net,c#-4.0,dynamic,delegates

params mean that compiler will do smart thing when you call the function to convert whatever arguments you've passed to array. It does not mean that function itself takes 1 or 2 parameters, and it does not mean there are 2 version of function f(dynamic target) and f(dynamic target, params...

Using delegates: unexpectedly found nil while unwrapping an Optional value

ios,swift,uiscrollview,delegates,uiscrollviewdelegate

Is visibleRect bound? It doesn't look to be. If that is bound, then you'll notice other uses of !... You need to bind your outlets (typically in InterfaceBuilder): @IBOutlet var scrollView: UIScrollView! @IBOutlet var inputImage:UIImageView! Perhaps scrollView is not bound and thus, because it is implicitly unwrapped (the ! operator),...

NSUrlConnection Delegate methods are not getting called from helper class

ios,delegates,nsurlconnection,nsurlconnectiondelegate

I'm wondering why would anyone use asynchronous request for performing task synchronously? Not to mention this strange way to wait with while statement instead of dispatch_semaphore or something similar. However, why You even bother with delegate? Just use class method sendSynchronousRequest:returningResponse:error:. I think, it would suffice in your case...

Custom Delegate with Modal Form Sheet not working

ios,objective-c,delegates

Here it goes Change DetailViewController.m - (IBAction)pushToSearch:(id)sender{ SearchModalViewController *searchModal = [self.storyboard instantiateViewControllerWithIdentifier:@"search"]; searchModal.searchDelegate = self; [self presentViewController:searchModal animated:YES completion:nil]; } And it will work....

C++ Generalize delegates

.net,callback,delegates,c++-cli

First of all if you expose Callbackfor1 and Callbackfor2 (I assume your class members are all public) then you don't also need RegisterCallback1 and RegisterCallback2: they're just helper methods that make caller code even more prolix: manager->RegisterCallback1(YourMethod); Instead of: manager->Callbackfor1 += YourMethod; However note that having your delegates public you're...

Location of event components in a multi class situation

c#,class,events,delegates

if you have class that detects value and you want to update a text box in a form Then declare/define the event in the class where it detects value and raise the event from that same class passing the parameter when it detected the value. In form (where you...

Delegates vs Calling of Functions [closed]

vb.net,delegates

Well, "the essential idea" of "delegation" is simply: "identify Someone Else that you can ask." In this example, the Compare class exists to "compare two objects." But you've said that it is to delegate that responsibility to some other function that is not a part of its own definition. Furthermore,...

Where to put Delgates in .Net Solution [closed]

c#,.net,delegates,namespace-organisation

I would assume the general consensus is that you place them anywhere that makes sense for the use case, but in general I feel there is a best way to structure everything in a solution to minimise problems, promote positive modularity, and ease maintenance. Well yes, in the general...

Delegate to private function as argument for method in different class

c#,delegates,function-pointers

You could create an Action argument to your method: public h(Action action) { action(); } and then call it like this: b.h(this.g); Possibly worth noting that there are generic versions of Action that represent methods with parameters. For example, an Action<int> would match any method with a single int parameter....

Remove jQuery delegated event handler on specific object

javascript,jquery,delegates,event-delegation

After having read thru on the web, the answer is you can't! You can either remove all or none. A workaround could be something like the following. $(document).on('click', '.btn', function (ev) { alert('pressed'); $(this).removeClass("btn"); }); [email protected] Sample HTML: <button class="btn">One</button> <button class="btn">Two</button> <button class="btn">Three</button> ...

Swift. Extending a delegate from a base class

ios,objective-c,swift,delegates,extend

I'd either create a wrapper delegate to make it the correct type in SubClass. class SubClass: BaseClass { var myDelegate: SubClassDelegate? { get { return delegate as? SubClassDelegate } set { delegate = newValue } } @IBAction func onDoSomething(sender: AnyObject) { myDelegate?.additionalSubClassDelegateMethod(); } } Or simply cast the delegate to...

How does apple set the Delegates of the UIKit classes as Outlets?

delegates,uikit,protocols

Yes you will need to the IBOutlet keyword to the delegate property. Like: @property (nonatomic, assign) IBOutlet id <YourDelegateClass> delegate; ...

What's the behaviour of setting multiple delegate on the same class Objective-C

objective-c,delegates

If the delegate protocol is defined correctly, each delegate method receives the delegated object, so you can perform educated choices. For example, - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section If you have three table views with the same data source (or delegate), you would know which one you are servicing from the tableView...

iOS callback function from library

ios,objective-c,delegates

You have 3 options Delegate Notification Block,also known callback I think what you want is Delegate Assume you have this file as lib TestLib.h #import <Foundation/Foundation.h> @protocol TestLibDelegate<NSObject> -(void)updateCount:(int)count; @end @interface TestLib : NSObject @property(weak,nonatomic)id<TestLibDelegate> delegate; -(void)startUpdatingCount; @end TestLib.m #import "TestLib.h" @implementation TestLib -(void)startUpdatingCount{ int count = 0;//Create count if...

how to write delegate with 2 parameters

c#,delegates,syntax-error

In order for the compiler to know if the , belongs to the constructor call or to the method signature of the delegate, you should add parenthesis around the delegate signature: var addCar = new Action<string, decimal>((number, test) => { } ); Now it reads the delegate as (number, test)...

C# Delegates. Casting not working for some reason

c#,casting,delegates

You have int TotalPay = CalculatePay(HourlyPay, HourlyPay, calc);, obviously it's a spelling, and you should have: int TotalPay = CalculatePay(HourlyPay, HoursPerShift, calc); BTW, local variables, as well as methods parameters, should be CamelCased....

Get the method name that was passed through a lambda expression?

.net,vb.net,reflection,delegates,pinvoke

I would not do this. It would be simpler to pass a string var representing the error message you want to display or a portion thereof (like the function name). The "simplest" way would be to use an Expression Tree. For this, you would need to change the signature of...

C# how cancel an executing method

c#,multithreading,delegates,thread-safety

Well; I find out a complicated, but effective, way to solve my problem: a.) I created a "Helper application" to show a notification icon when the process is running (To ensure to don't interfere with the normal execution of the main app): private void callHelper(bool blnClose = false) { if...

Groovy multiple Delegate annotation/Wrapper for list

list,groovy,delegates,annotations

Short answer: reaplce += with add You problem is not @Delegate, but misunderstanding what += does. See this example: def l = [1,2,3] l += [4,5] assert l == {1,2,3,4,5] As you can see, the list [4,5] is not added as list. Instead a new list consisting of the elements...

Does System.Action keep a weak reference to the owner of the method?

c#,delegates

All delegates hold a strong reference to both an object instance (when not referencing a static method) and a method to execute on that instance. Keeping the delegate alive will keep the object (if there is one) that the delegate invokes its method on alive.

How to use a function from the view controller in the app delegate?

ios,objective-c,delegates

One word: NSNotificationCenter I'm not sure what you need to set the data to because you can't pass the data seamlessly via NSNotificationCenter; however you were going to figure that out in your UIApplicationDelegate anyway, so why can't you do it in the view controller directly. In your case there...

Closures vs Delegate pattern

ios,swift,delegates,closures

So, when the callback finally gets fired, self.myLabel.text might result in a crash, as the View Controller to whom self was referring could already be deallocated. If self has been imported into the closure as a strong reference, it is guaranteed that self will not be deallocated up until...

Swift equivalent of id?

objective-c,swift,delegates,protocols

A protocol is a type, so you can use it as a declared variable type. To use weak, you must wrap the type as an Optional. So you would say: weak var delegate : MyDelegate? But in order for this to work, MyDelegate must be an @objc or class protocol,...

What are protocols and delegates and how are they used in IOS? [duplicate]

ios,objective-c,delegates,protocols

Yes, protocol is analogous to interface in Java. If an object conforms to a protocol, it has to implement all selectors defined in this protocol. Objective C simply has a different concept of interface (every class is split into interface and implementation), so this word was already taken, I guess....

Programmatically switching tabBar causes IBOutlet to be nil

ios,swift,delegates,uitabbarcontroller,iboutlet

The problem is that you're creating a new instance of MapViewController when you set the delegate with the below line. That instance isn't made in the storyboard, so it knows nothing about your IBOutlet. delegate = MapViewController() You need to get a reference to the controller that already exists. If...

Create generic Func from reflection

c#,reflection,delegates

You can solve this by building an expression tree manually, and inserting a cast to hiddenType. This is allowed when you construct an expression tree. var typeConst = Expression.Constant(hiddenType); MethodInfo getInst = ... // <<== Use reflection here to get GetInstance info var callGetInst = Expression.Call(getInst, typeConst); var cast =...

How to get tableview cell text label from 2nd viewcontroller to a label from 1st viewcontroller?

ios,uitableview,delegates,nsnotifications

1st In VC2, you must create delegate @protocol VC2Delegate; @interface VC2 : UIViewController @property (nonatomic, weak) id <VC2Delegate> delegate; @end @protocol VC2Delegate <NSObject> @required - (void)changeToText:(NSString *)text; @end @implementation VC2 // this is your "完了" action - (IBAction)doneAction:(id)sender { ... [self.delegate changeToText:@"what you want"]; } @end 2nd, add the delegate...

C# language doesn't need the concept of delegates? [closed]

java,c#,c++,callback,delegates

C++ had "official" (non-Boost) "full" delegates from C++11 (std::function)... Before that, getting a pointer to a member function was always a little hackish... So I wouldn't consider C++ to be a good comparison :-) And C++ can overload the round parenthesis, so it is more easy to "hide" the hacks...

No visible @interface for 'UIViewController' declares the selector

ios,objective-c,delegates,nsurlconnection

You typed viewController as a UIViewController when you declared it. You need to type it as a LoginViewController. You also shouldn't be declaring both an ivar and a property. Just declare the property, and delete the two ivars.

How extract parameters passed by delegate parameter

c#,parameters,delegates,helpers

In order to retrieve the body (since it would have been compiled and JIT'ed away into a much different state by the time you tried to retrieve it), you would need an Expression<Action<T>>. However, you cannot convert lambda statement bodies to expression trees. As a result, you may be better...

How to filter a collection of delegates based on their parameter's generic type in C#?

c#,linq,generics,delegates

This not be the prettiest thing ever, but it works var aDelegates = someClass.Delegates.Where(d => d.Method.DeclaringType.GenericTypeArguments.FirstOrDefault().IsAssignableFrom(typeof(SomeInterfaceImplA))); ...

UI Slow to Update *ONLY* If Called In Response To Change Occurring in NSURLSessionUploadTask Completion Block

ios,objective-c,delegates,nsurlsession,nsurlsessionuploadtask

Use main queue to update the UI. Use following code: - (void)priceDidUpdate:(NSString *)updatedPrice { dispatch_async(dispatch_get_main_queue(), ^() { //Add method, task you want perform on mainQueue //Control UIView, IBOutlet all here NSLog(@"priceDidUpdate delegate notification - updatedPrice is: %@", updatedPrice); [self.deliveryLabel setText:@"N/A"]; [self.priceLabel setText:updatedPrice]; }); } ...

Why do generic delegates have DelegateName(T arg)? Why not DelegateName(T arg)

c#,generics,delegates

A delegate is a class behind the scenes, and needs a type specifier to be generic. You'll note how a declaration of a class like: class MyList { T[] items; } is invalid, because T is unknown in that context. Delegates need a type declaration for the same reason -...

Calling delegate with multiple functions having return values

c#,delegates

Actually, with a little bit of trickery and casting, you can get all of the results like this: var b = new BinaryOp(Add); b += new BinaryOp(Multiply); var results = b.GetInvocationList().Select(x => (int)x.DynamicInvoke(2, 3)); foreach (var result in results) Console.WriteLine(result); With output: 5 6 ...

Can't remove methods from delegate object invocation list properly

c#,delegates

You've got two different syntaxes here: DelegateType x = new DelegateType(MethodName) DelegateType x = new DelegateType(ExistingDelegateInstance) Those do different things - the first builds a new delegate instance based on a method group conversion. That's entirely equivalent to just: DelegateType x = MethodName; The second builds a new delegate instance...

RACDelegateProxy vs Common Delegate implementation

ios,delegates,reactive-cocoa

Your question can be generalised to "What are the advantages of signals over callbacks". There used to be a link on RAC's github repo called Escape from Callback Hell - link is no longer working, but I think that title highlights the point perfectly. Basically, one of the advantages of...

Implementing Nuance Speech Recognition on Swift, cannot listen to onResult, onError… events

ios,swift,delegates,speech-recognition,header-files

Here's what I've got Bridging Header: #import <SpeechKit/SpeechKit.h> #import "NuanceHeader.h" NuanceHeader.h: #import <Foundation/Foundation.h> @interface NuanceHeader : NSObject @end NuanceHeader.m #import "NuanceHeader.h" const unsigned char SpeechKitApplicationKey[] = {...}; @implementation NuanceHeader @end When it comes to the UIViewController that uses all this: class MyViewController: UIViewController, SpeechKitDelegate, SKRecognizerDelegate { var voiceSearch: SKRecognizer? override...

C# How to notify other classes with a single timer?

c#,timer,delegates

I can point out 2 options: Create an interface like TimerControlled (all names can be changed) With a method TimerTick(whatever arguments you need) (and others if needed) , which implements your timer tick logic for that class. Implement the interface the on each class that uses timer dependent mechanics. Finally...

OS X Delegate set label from other window (Xcode)

objective-c,xcode,osx,delegates

SOLVED. (Thanks to Phillip Mills) NSNotification is way simpler and efficient than Delegates in this case. ViewController.m [...] - (void)viewDidLoad { [super viewDidLoad]; [email protected]"TEST"; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdatedData:) name:@"DataUpdated" object:nil]; } -(void)handleUpdatedData:(NSNotification *)notification { NSLog(@"recieved %@", notification); txtlabel.stringValue=[notification object]; } secondController.m -(IBAction)submit:(id)sender { NSString *txtval=...

How to use delegates to communicate data from a custom cell to a label in the parent view

ios,uitableview,swift,delegates,protocols

You should set the delegate here: func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("thisCustomCell", forIndexPath: indexPath) as! CellViewController cell.delegate = self // <-- Set the delegate. return cell } ...

Dynamic where expression to use in linq

c#,lambda,delegates

Copy of comment: I got your problem. You create a new ParameterExpression for EACH property. They're all called x but they're different instances. Create only one ParameterExpression called x and then loop over all properties....

Are Func and Action Delegates in C# used by companies?

c#,events,delegates,action,func

In C#, Action and Func are extremely useful tools for reducing duplication in code and decreasing coupling. And reduce duplication and make code reusable is important to any company It is a shame that many developers shy away from them because they don’t really understand them. Adding Action and Func...

Need clarification on delegates in iOS [closed]

ios,objective-c,delegates

In the case of UIAlertView, yes, UIAlertView is a delegating object and whatever its delegate property points to is its delegate. For everything in Apple's built-in frameworks, the delegating object will typically have a property called delegate. The delegating object is the one which has this property (which is where...

Implementing delegate methods in separate class

ios,iphone,uiviewcontroller,delegates

You can use a separate class dedicated to the delegate methods, or use a view controller subclass, which every other VC will inherit from.

Automatically delegating all methods of a java class

java,reflection,delegates

Perhaps the dynamic Proxy of java can help you. It only works if you consequently use interfaces. In this case, I will call the interface MyInterface and set up a default implementation: public class MyClass implements MyInterface { @Override public void method1() { System.out.println("foo1"); } @Override public void method2() {...

Delegate was not declared?

ios,objective-c,delegates

Put your protocol declaration in its own Protocols.h file, for example: //Protocols.h @protocol mainScrollerDelegate <NSObject> -(void)function; @end Then, just import it into both the controller who is sending the delegate methods, and the delegate itself: #import "Protocols.h" @interface MyPillsView : UIViewController <mainScrollerDelegate> This method will keep all your protocols organized...

Adding protocols for dynamically created UIPickerView

ios,objective-c,delegates,protocols,uipickerview

You are trying to set a class as delegate. Do set an instance to resolve this issue. UIPickerView *pv = [[UIPickerView alloc] initWithFrame:CGRectMake(x, y, width, height)]; pv.delegate = self; instead of UIPickerView *pv = [[UIPickerView alloc] initWithFrame:CGRectMake(x, y, width, height)]; Class<UIPickerViewDelegate, UIPickerViewDataSource> delegatedClass = (Class<UIPickerViewDelegate, UIPickerViewDataSource>)[self class]; pv.delegate = delegatedClass;...

Events - Publish & Subscribe

c#,events,delegates

Under what conditions do you want your handlers to fire? You can have the following pattern which will provide a mechanism to prevent the handlers firing based on a unique identifier. In this example, I create some simple event args which the event will use to tell the handler a...

Can you use equals assignment when removing delegate members in a disposing method?

c#,delegates,operators,variable-assignment,dispose

There's no reason not to just assign null to the delegate here. You wouldn't be able to just assign null if you were outside of the class that defined the event. To anyone using the class they should only be concerned with their own handlers, that they can add or...

specify type of delegate parameter

c#,dictionary,delegates,action,trygetvalue

action needs to be declared locally in the delegate, not as a parameter. Method(null, "mesh", ( () => //How to specify type of action { Action<Mesh> action; _meshActions.TryGetValue(_reader.LocalName, out action); try { action(mesh); } catch { //do nothing } })); ...

Accept any type as delegate parameter

c#,unity3d,delegates

This type doesn't need to bother supporting this. Simply accept an Action and support no other delegates. If the caller would like to call a method that has parameters and provide those parameters they can use a lambda to close over the values in question, giving you your Action but...

Understanding the event usage wrt delegates and registration methods

c#,events,delegates

Your two cases are nearly identical. The only material difference is that when you use an event in your class (i.e. "case 2"), and you don't implement it explicitly, the compiler automatically generates the field that you would have had to declare in "case 1", as well as the method...

Passing delegates as parameters for mediator/subscriber pattern

c#,events,delegates,params,mediator

You should take a different approach: let your senders dispatch messages, and have your mediator dispatch them to different handlers based on their type. Using generics, this would be refactored to: // handlers should be differentiated by message type public class SomethingHappenedMessage { public float A { get; set; }...

Swift - label not updating in WatchKit from delegate callback

ios,swift,delegates,watchkit

You can only update interface elements during initialization and when an interface controller is considered "active." A WKInterfaceController is active between the willActivate and didDeactivate calls. Specifically, you can update the interface within willActivate, but you cannot update during didDeactivate. When you call your delegate, it will have to remember...

How to edit the main form in C# from a timer?

c#,timer,delegates

I'm not positive I understand your problem, but it sounds like you're having an issue updating the UI from a background thread? If so, try this: timer.Start() starts a new thread separate from your Winform's UI thread, so you may need to Invoke your WinForm's thread in order to see...

Understanding Func Delegate with MVC

c#,asp.net-mvc,razor,delegates

The Html property (@Html) is of type HtmlHelper<Products>, because of the @model Products directive. This is how the Razor engine works. TextBoxFor is an extension method to HtmlHelper<TModel>, and in your code, you're calling it on an instance of HtmlHelper<Products>, therefore TModel is resolved to Products. Then, the compiler can...

How does QLineEdit triger QAbstractItemDelegate::commitData

qt,delegates,qlineedit,qabstractitemmodel

The QStyledItemDelegate (and QItemDelegate) defines an event filter that calls commitData if you press tab or return. See the following excerpt from the Qt 4.8.6 source: bool QStyledItemDelegate::eventFilter(QObject *object, QEvent *event) { QWidget *editor = qobject_cast<QWidget*>(object); if (!editor) return false; if (event->type() == QEvent::KeyPress) { switch (static_cast<QKeyEvent *>(event)->key()) { case...

Delegate called multiple times from asynchronous WCF method

c#,wcf,delegates

Every time a call to doActiveDx is performed, the delegate is registered once again. This results in multiple calls to the delegate on subsequent calls to doActiveDx. Make sure you are registering the delegate just once. For instance, try registering it outside the doActiveDx function....

C++ Java Handler equivilent

c++,callback,delegates

Pretty much the same as you'd do it in Java. In your library, define a pure virtual class (more-or-less analogous with Java interface) of the handler. class somethinghandler { public: virtual void somethinghappened(<stuff that happened>) = 0; } And define and implement a class to watch for the event and...

iOS: pass data to another class

ios,swift,delegates,block,delegation

func requestDocuments(completion:(data:NSArray?)){ request(.POST, "http://example.com/json/docs") .responseJSON { (_, _, JSON, error) in if error == nil{ var response = JSON as NSArray println("array document: \(response)") //**** HERE I WANT PASS VALUE TO MY VIEW CONTROLLER completion(data:response) } else{ completion(data:nil) } } } var reqDoc = requestDocuments(){ (data) -> Void in if...

iOS Swift Delegate Syntax

ios,swift,delegates

The full method name is pickerView:numberOfRowsInComponent but the component is the parameter name that will actually contain passed value Read about External Parameter Names Sometimes it’s useful to name each parameter when you call a function, to indicate the purpose of each argument you pass to the function. If you...

What is the proper way to declare a delegate variable?

cocoa,delegates,xcode6,protocols

The main difference comes along when you type something as id <SomeProtocol> and then try to send it a message such as respondsToSelector: and the compiler won't let you. It comes as a surprise - or at least it sure came as a surprise to me - that id <SomeProtocol>...

How to store Action delegates with constrained generic type in a type safe collection in C#?

c#,generics,delegates

_delegates has to be of type IList<Action<T>>. Therefore you have to add the <T> where T : ISomething to the class. Alternatively, do away with the generics and support Action<ISomething> directly. So your two options are: public class Delegates<T> where T : ISomething { private List<Action<T>> _delegates; public void AddDelegate(Action<T>...

Receive delegate method calls from multiple view controllers

ios,swift,uiviewcontroller,delegates,uisplitviewcontroller

This is a best-practice case for a Singleton-pattern Your DataLoader should implement a static let holding the reference to the same object of self. static let sharedInstance = DataLoader() When you want the reference to constantly the same singleton-object. Call it with DataLoader.sharedInstance Make sure to always use .sharedInstance then...

Is there any reason to use a function with a void return over an Action in C#?

c#,function,delegates,action

Sure, there are plenty of good reasons. The first three to come to mind: Pretty much any C# programmer will be highly surprised by your extremely uncommon overuse of delegates. Functions can be virtual, and can be used to implement interfaces. Variables, even variables of delegate type, can be re-assigned,...

Convert Func to Delegate [duplicate]

c#,.net,c#-4.0,dynamic,delegates

You can wrap the existing delegate: (MyDelegate)(x => myFunc(x)) Or equivalently: MyDelegate myDeleg = x => myFunc(x); This causes a small performance loss on each invocation but the code is very simple....

delegate for all methods

c#,delegates

Well, there is the Delegate. private Queue<Delegate> TaskQueue; ... public void AddTask(Delegate task) { this.TaskQueue.Enqueue(task); } However, when adding a task using AddTask, it won't be that easy as before. You'll first need to convert into a known delegate (Func<>), and then pass an argument. obj.AddTask((Func<...>)nameOfTheMethod); // obj.AddTask((Func<string[], void>)Console.WriteLine); When...

Direct create function while defining the method

c#,events,printing,delegates

Yes, you need to create a lambda expression, as follows: printDocument1.PrintPage += (s, e) => { // Method code goes here // The variable s represents the first parameter, "object sender" // The variable e represents the second parameter, "PrintPageEventArgs e" }; This will create an anonymous method using a...

How to assign textfield or any delegate in Swift Language?

swift,delegates,uitextfield

You need to add Protocols you want to conform using comma: class LoginViewController: UIViewController, UITextFieldDelegate You can only extend only from one class, but conform with as many protocols as you want: class LoginViewController: UIViewController, UITextFieldDelegate, UIAlertViewDelegate From Apple doc: class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol { // class definition goes...

ContainerViewController delegate to ChildViewController

ios,objective-c,uiviewcontroller,delegates

You never set the delegate, so self.delegate will be nil. You should do this, - (void)viewDidLoad { _childViewController = [[WeeklyViewController alloc]init]; self.delegate = _childViewController; [self addChildViewController:_childViewController]; [self.view addSubview:_childViewController.view]; [_childViewController didMoveToParentViewController:self]; } ...

How to Invoke dynamicaly an anonymus objects function property?

c#,delegates,system.reflection,anonymous-class

You can't create methods in an anonymous object. You can only have properties (that can be delegates)... So: Type type = ERRORS.GetType(); // Properties: PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo property in properties) { // Get the value of the property, cast it to the right type Func<bool> func =...

Typhoon injection and setting delegate

ios,swift,dependency-injection,delegates,typhoon

I recommend using the typhoonDidInject callback method typhoonDidInject() -> Void { myObject.delegate = self; } or if you don't wish to couple directly to Typhoon, specify a custom one in the assembly: definition.performAfterInjections("someMethod") I can't think of a neater way to wire all of this up in the assembly, however...