Search Results

Search found 577 results on 24 pages for 'delegates'.

Page 5/24 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • If I write a framework that gets information from the Internet, should I make a degelate or use blocks?

    - by Time Machine
    Say I'm writing a publicly available framework for the Vimeo API. This framework needs to get information from the Internet. Because this can take some time, I need to use threadin to prevent the UI from hanging. Foundation uses delegates for this, like NSURLConnectionDelegate. However, Game Kit uses blocks as callback functions. What is the recommended way of doing this? I know blocks aren't supported in standard GCC versions, but they require less, much less code for the one that uses my framework. Delegates, on the other hand, are real methods and when protocols are used, I'm sure the methods are implemented. Thanks.

    Read the article

  • List<object>.RemoveAll - How to create an appropriate Predicate

    - by CJM
    This is a bit of noob question - I'm still fairly new to C# and generics and completely new to predicates, delegates and lamda expressions... I have a class 'Enquiries' which contains a generic list of another class called 'Vehicles'. I'm building up the code to add/edit/delete Vehicles from the parent Enquiry. And at the moment, I'm specifically looking at deletions. From what I've read so far, it appears that I can use Vehicles.RemoveAll() to delete an item with a particular VehicleID or all items with a particular EnquiryID. My problem is understanding how to feed .RemoveAll the right predicate - the examples I have seen are too simplistic (or perhaps I am too simplistic given my lack of knowledge of predicates, delegates and lambda expressions). So if I had a List<Of Vehicle> Vehicles where each Vehicle had an EnquiryID, how would I use Vehicles.RemoveAll() to remove all vehicles for a given EnquiryID? I understand there are several approaches to this so I'd be keen to hear the differences between approaches - as much as I need to get something working, this is also a learning exercise. As an supplementary question, is a Generic list the best repository for these objects? My first inclination was towards a Collection, but it appears I am out of date. Certainly Generics seem to be preferred, but I'm curious as to other alternatives. Thanks

    Read the article

  • How to defer execution of an Event on each item in a collection until iteration of collection is com

    - by Metro Smurf
    Of Note: This is more of a curiosity question than anything else. Given a List<Window> where each window has an event attached to the Close Event which removes the window from the collection, how could you use delegates / events to defer the execution of the Close Event until the collection has been iterated? For example: public class Foo { private List<Window> OpenedWindows { get; set; } public Foo() { OpenedWindows = new List<Window>(); } public void AddWindow( Window win ) { win.Closed += OnWindowClosed; OpenedWindows.Add( win ); } void OnWindowClosed( object sender, EventArgs e ) { var win = sender as Window; if( win != null ) { OpenedWindows.Remove( win ); } } void CloseAllWindows() { // obviously will not work because we can't // remove items as we iterate the collection // (the close event removes the window from the collection) OpenedWindows.ForEach( x => x.Close() ); // works fine, but would like to know how to do // this with delegates / events. while( OpenedWindows.Any() ) { OpenedWindows[0].Close(); } } } Specifically, within the CloseAllWindows() method, how could you iterate the collection to call the close event, but defer the event being raised until the collection has been completely iterated?

    Read the article

  • Action Delegate C#

    - by user275561
    So I read MSDN, And stackoverflow. I understand what the Action Delegate does in general but it is not clicking no matter how many examples I do. In General same goes for the idea of delegates. So here is my question when you have a function like this public GetCustomers(Action<IEnumerable<Customer>,Exception> callBack) { } I just Dont have a clue on what is that or what should i pass to it.

    Read the article

  • When to call release on NSURLConnection delegate?

    - by Kieran H
    Hi, When passing a delegate to the a NSUrlConnection object like so: [[NSURLConnection alloc] initWithRequest:request delegate:handler]; when should you call release on the delegate? Should it be in connectionDidFinishLoading? If so, I keep getting exec_bad_access. I'm seeing that my delegates are leaking through instruments. Thanks

    Read the article

  • NSNotifications vs delegate for multiple instances of same protocol

    - by Brent Traut
    I could use some architectural advice. I've run into the following problem a few times now and I've never found a truly elegant way to solve it. The issue, described at the highest level possible:I have a parent class that would like to act as the delegate for multiple children (all using the same protocol), but when the children call methods on the parent, the parent no longer knows which child is making the call. I would like to use loose coupling (delegates/protocols or notifications) rather than direct calls. I don't need multiple handlers, so notifications seem like they might be overkill. To illustrate the problem, let me try a super-simplified example: I start with a parent view controller (and corresponding view). I create three child views and insert each of them into the parent view. I would like the parent view controller to be notified whenever the user touches one of the children. There are a few options to notify the parent: Define a protocol. The parent implements the protocol and sets itself as the delegate to each of the children. When the user touches a child view, its view controller calls its delegate (the parent). In this case, the parent is notified that a view is touched, but it doesn't know which one. Not good enough. Same as #1, but define the methods in the protocol to also pass some sort of identifier. When the child tells its delegate that it was touched, it also passes a pointer to itself. This way, the parent know exactly which view was touched. It just seems really strange for an object to pass a reference to itself. Use NSNotifications. The parent defines a separate method for each of the three children and then subscribes to the "viewWasTouched" notification for each of the three children as the notification sender. The children don't need to attach themselves to the user dictionary, but they do need to send the notification with a pointer to themselves as the scope. Same as #4, but rather than using separate methods, the parent could just use one with a switch case or other branching along with the notification's sender to determine which path to take. Create multiple man-in-the-middle classes that act as the delegates to the child views and then call methods on the parent either with a pointer to the child or with some other differentiating factor. This approach doesn't seem scalable. Are any of these approaches considered best practice? I can't say for sure, but it feels like I'm missing something more obvious/elegant.

    Read the article

  • Is there an existing delegate in the .NET Framework for comparison?

    - by Neil Barnwell
    The .NET framework provides a few handy general-use delegates for common tasks, such as Predicate<T> and EventHandler<T>. Is there a built-in delegate for the equivalent of CompareTo()? The signature might be something like this: delegate int Comparison<T>(T x, T y); This is to implement sorting in such a way that I can provide a lambda expression for the actual sort routine (ListView.ListViewItemSorter, specifically), so any other approaches welcome.

    Read the article

  • Best practice for controlling a busy GUI

    - by MPelletier
    Suppose a GUI (C#, WinForms) that performs work and is busy for several seconds. It will still have buttons that need to remain accessible, labels that will change, progress bars, etc. I'm using this approach currently to change the GUI when busy: //Generic delegates private delegate void SetControlValue<T>(T newValue); //... public void SetStatusLabelMessage(string message) { if (StatusLabel.InvokeRequired) StatusLabel.BeginInvoke(new SetControlValue<string>(SetStatusLabelMessage, object[] { message }); else StatusLabel.Text = message; } I've been using this like it's going out of style, yet I'm not quite certain this is proper. Creating the delegate (and reusing it) makes the whole thing cleaner (for me, at least), but I must know that I'm not creating a monster...

    Read the article

  • Dictionary with delegate or swith?

    - by Samvel Siradeghyan
    Hi, I am writting a parser, which call some functions dependent on some value. I can implement this logic with simple switch like this swith(some_val) { case 0: func0(); break; case 1: func1(); break; } or with delegates and dictinary like this delegate void some_delegate(); Dictinary some_dictinary = new Dictinary(); some_dictinary[0] = func0; some_dictinary[1] = func1; some_dictinary[some_value].Invoke(); Are this two metods equal and wich is prefered? Thanks.

    Read the article

  • Dictionary with delegate or switch?

    - by Samvel Siradeghyan
    Hi, I am writing a parser, which call some functions dependent on some value. I can implement this logic with simple switch like this switch(some_val) { case 0: func0(); break; case 1: func1(); break; } or with delegates and dictionary like this delegate void some_delegate(); Dictionary<int, some_delegate> some_dictionary = new Dictionary<int, some_delegate>(); some_dictionary[0] = func0; some_dictionary[1] = func1; some_dictionary[some_value].Invoke(); Are this two methods equal and which is preferred? Thanks.

    Read the article

  • Why can't I use an Action to a ThreadStart?

    - by Rookian
    Both are delegates and have the same signature, but I can not use Action as ThreadStart. Why? Action doIt; doIt = () => MyMethod("test"); Thread t; t = new Thread(doIt); t.Start(); but this seams to work: Thread t; t = new Thread(() => MyMethod("test")); t.Start();

    Read the article

  • How can I safely raise events in an AsyncCallback?

    - by cyclotis04
    I'm writing a wrapper class around a TcpClient which raises an event when data arrives. I'm using BeginRead and EndRead, but when the parent form handles the event, it's not running on the UI thread. I do I need to use delegates and pass the context into the callback? I thought that callbacks were a way to avoid this... void ReadCallback(IAsyncResult ar) { int length = _tcpClient.GetStream().EndRead(ar); _stringBuilder.Append(ByteArrayToString(_buffer, length)); BeginRead(); OnStringArrival(EventArgs.Empty); }

    Read the article

  • Sending information back from delegate [iPhone]

    - by Andy
    I'm using NSXMLParser in my RootViewController.m file. NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:response_data]; [xmlParser setDelegate:self]; [xmlParser parse]; [xmlParser release]; I'm also implementing this method to add entries to a dictionary defined in RootViewController.m for later use: - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict However, I'd like to get more than one XML file and do different things when the file has finished; this sounds like I need to use external files as delegates. My question is: If I have the following implementation files (& their header files): RootViewController.m XMLDelegate1.m XMLDelegate2.m and set the ith NSXMLParser delegate to be XMLDelegatei.m, and get those files to return an NSDictionary that I can then add to the NSDictionary defined in RootViewController.m. I guess there are two methods of doing this: Use a method that I don't know about; or Use a better workflow I suspect it's 2, but hope it's 1. Thanks, Andy

    Read the article

  • Using a delegate to populate a listbox

    - by Leroy Jenkins
    Ive been playing around with delegates trying to learn and I ran into one small problem Im hoping you can help me with. class myClass { OtherClass otherClass = new OtherClass(); // Needs Parameter otherClass.SendSomeText(myString); } class OtherClass { public delegate void TextToBox(string s); TextToBox textToBox; public OtherClass(TextToBox ttb) // ***Problem*** { textToBox = ttb; } public void SendSomeText(string foo) { textToBox(foo); } } the form: public partial class MainForm : Form { OtherClass otherClass; public MainForm() { InitializeComponent(); otherClass = new OtherClass(this.TextToBox); } public void TextToBox(string aString) { listBox1.Items.Add(aString); } } Obviously this doesnt compile because the OtherClass constructor is looking for TextToBox as a parameter. How would you recommend getting around the issue so I can get an object from myClass into the textbox in the form?

    Read the article

  • very simple delegate musing

    - by Ted
    Sometimes the simplest questions make me love C/C++ and C# more and more. Today sitting on the bus musing aout delegates I remembered reading somwhere you don't need to use the new keyword when instaniating a new delegate. For example: public static void SomeMethod(string message) { ... } ... public delegate void TestDelgate(string message); //Define a delegate ........... //create a new instance ..METHOD 1 TestDelgate t = new TestDelgate(SomeMethod); //OR another way to create a new instance ..METHOD 2 TestDelgate t = SomeMethod; //create a new instance ..METHOD 2 So todays questions are What happens under the hood in method 2. Does the compiler expand method 2 into method 1, hence writing TestDelgate t = SomeMethod; is just a shortcut for TestDelgate t = new TestDelgate(SomeMethod);, or is there another reason for the exsitence of method 2 Do you guys think method 1 or method 2 is better for readability (this is a subjective question, but I'd just like to get a unscientific feel of general opinion of stackoverflow :-))

    Read the article

  • How to create a static delegate from main-viewcontroller?

    - by geforce
    Hi, hope someone can help me on learning some new stuff about delegates in iOS-programming. I have a "MainViewController" which is the first VC when the app starts. I´ve a kind of modelselection with different UIImageViews and after choosing one of them, i´m pushing a new VC. I want to handle the modelChoice with a delegate, so all other viewControllers can listen to that and act based on the users choice. But does that mean that i have to alloc a new instance of that "MainViewController" in every VC? Whats the solution on that? How do i create (i think its called) static delegate? Would be great to learn that.. Thanks for sharing..

    Read the article

  • Delegate.CreateDelegate() and generics: Error binding to target method

    - by SDReyes
    I'm having problems creating a collection of delegate using reflection and generics. I'm trying to create a delegate collection from Ally methods, whose share a common method signature. public class Classy { public string FirstMethod<out T1, in T2>( string id, Func<T1, int, IEnumerable<T2>> del ); public string SecondMethod<out T1, in T2>( string id, Func<T1, int, IEnumerable<T2>> del ); public string ThirdMethod<out T1, in T2>( string id, Func<T1, int, IEnumerable<T2>> del ); // And so on... } And the generics cooking: // This is the Classy's shared method signature public delegate string classyDelegate<out T1, in T2>( string id, Func<T1, int, IEnumerable<T2>> filter ); // And the linq-way to get the collection of delegates from Classy ( from method in typeof( Classy ).GetMethods( BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.NonPublic ) let delegateType = typeof( classyDelegate<,> ) select Delegate.CreateDelegate( delegateType, method ) ).ToList( ); But the Delegate.CreateDelegate( delegateType, method ) throws an ArgumentException saying Error binding to target method. : / What am I doing wrong?

    Read the article

  • Example usage of a custom delegate in c#

    - by Freakishly
    Hi, I found this question on SO about a tree implementation in C#. I have no idea about delegates and I was wondering how the following code could be used to implement a tree. Also, what would be the most efficient way to keep a track of parent nodes? delegate void TreeVisitor<T>(T nodeData); class NTree<T> { T data; LinkedList<NTree<T>> children; public NTree(T data) { this.data = data; children = new LinkedList<NTree<T>>(); } public void addChild(T data) { children.AddFirst(new NTree<T>(data)); } public NTree<T> getChild(int i) { foreach (NTree<T> n in children) if (--i == 0) return n; return null; } public void traverse(NTree<T> node, TreeVisitor<T> visitor) { visitor(node.data); foreach (NTree<T> kid in node.children) traverse(kid, visitor); } }

    Read the article

  • How to use delegate to perform callback between caller and web service helper class?

    - by codemonkie
    I have 2 classes A and B, where they belongs to the same namespace but resides in seperate files namely a.cs and b.cs, where class B essentially is a helper wrapping a web service call as follow: public class A { public A() // constructor { protected static B b = new B(); } private void processResult1(string result) { // come here when result is successful } private void processResult2(string result) { // come here when result is failed } static void main() { b.DoJobHelper(...); } } public class B { private com.nowhere.somewebservice ws; public B() { this.ws = new com.nowhere.somewebservice(); ws.JobCompleted += new JobCompletedEventHandler(OnCompleted); } void OnCompleted(object sender, JobCompletedEventArgs e) { string s = e.Result; Guid taskID = (Guid)e.UserState; switch (s) { case "Success": // Call processResult1(); break; case "Failed": // Call processResult2(); break; default: break; } } public void DoJobHelper() { Object userState = Guid.NewGuid(); ws.DoJob(..., userState); } } (1) I have seen texts on the net on using delegates for callbacks but failed to apply that to my case. All I want to do is to call the appropriate processResult() method upon OnCompleted() event, but dunno how to and where to declare the delegate: public delegate void CallBack(string s); (2) There is a sender object passed in to OnCompleted() but never used, did I miss anything there? Or how can I make good use of sender? Any helps appreciated.

    Read the article

  • How can I get this dynamic WHERE statement in my LINQ-to-XML to work?

    - by Edward Tanguay
    In this question Jon Skeet offered a very interesting solution to making a LINQ-to-XML statement dynamic, but my knowledge of lambdas and delegates is not yet advanced enough to implement it: I've got it this far, but of course I get the error "smartForm does not exist in the current context": private void LoadWithId(int id) { XDocument xmlDoc = null; try { xmlDoc = XDocument.Load(FullXmlDataStorePathAndFileName); } catch (Exception ex) { throw new Exception(String.Format("Cannot load XML file: {0}", ex.Message)); } Func<XElement, bool> whereClause = (int)smartForm.Element("id") == id"; var smartForms = xmlDoc.Descendants("smartForm") .Where(whereClause) .Select(smartForm => new SmartForm { Id = (int)smartForm.Element("id"), WhenCreated = (DateTime)smartForm.Element("whenCreated"), ItemOwner = smartForm.Element("itemOwner").Value, PublishStatus = smartForm.Element("publishStatus").Value, CorrectionOfId = (int)smartForm.Element("correctionOfId"), IdCode = smartForm.Element("idCode").Value, Title = smartForm.Element("title").Value, Description = smartForm.Element("description").Value, LabelWidth = (int)smartForm.Element("labelWidth") }); foreach (SmartForm smartForm in smartForms) { _collection.Add(smartForm); } } Ideally I want to be able to just say: var smartForms = GetSmartForms(smartForm=> (int) smartForm.Element("DisplayOrder").Value > 50); I've got it this far, but I'm just not grokking the lambda magic, how do I do this? public List<SmartForm> GetSmartForms(XDocument xmlDoc, XElement whereClause) { var smartForms = xmlDoc.Descendants("smartForm") .Where(whereClause) .Select(smartForm => new SmartForm { Id = (int)smartForm.Element("id"), WhenCreated = (DateTime)smartForm.Element("whenCreated"), ItemOwner = smartForm.Element("itemOwner").Value, PublishStatus = smartForm.Element("publishStatus").Value, CorrectionOfId = (int)smartForm.Element("correctionOfId"), IdCode = smartForm.Element("idCode").Value, Title = smartForm.Element("title").Value, Description = smartForm.Element("description").Value, LabelWidth = (int)smartForm.Element("labelWidth") }); }

    Read the article

  • XML comments on delegate declared events

    - by Matt Whitfield
    I am visiting some old code, and there are quite a few events declared with delegates manually rather than using EventHandler<T>, like this: /// <summary> /// Delegate for event Added /// </summary> /// <param name="index">Index of the item</param> /// <param name="item">The item itself</param> public delegate void ItemAdded(int index, T item); /// <summary> /// Added is raised whenever an item is added to the collection /// </summary> public event ItemAdded Added; All well and good, until I come to use sandcastle to document the library, because it then can't find any XML comments for the private Added field that is generated by the event declaration. I want to try and sort that out, but what I would like to do is either: Get sandcastle to ignore the auto-generated private field without telling it to ignore all private fields entirely or Get XML comments generated for the private field Is there any way of achieving this without re-factoring the code to look like this: /// <summary> /// Delegate for event <see cref="Added"/> /// </summary> /// <param name="index">Index of the item</param> /// <param name="item">The item itself</param> public delegate void ItemAdded(int index, T item); /// <summary> /// Private storage for the event firing delegate for the <see cref="Added"/> event /// </summary> private ItemAdded _added; /// <summary> /// Added is raised whenever an item is added to the collection /// </summary> public event ItemAdded Added { add { _added += value; } remove { _added -= value; } }

    Read the article

  • [C#] How to use delegate to perform callback between caller and web service helper class?

    - by codemonkie
    I have 2 classes A and B, where they belongs to the same namespace but resides in seperate files namely a.cs and b.cs, where class B essentially is a helper wrapping a web service call as follow: public class A { public A() // constructor { protected static B b = new B(); } private void processResult1(string result) { // come here when result is successful } private void processResult2(string result) { // come here when result is failed } static void main() { b.DoJobHelper(...); } } public class B { private com.nowhere.somewebservice ws; public B() { this.ws = new com.nowhere.somewebservice(); ws.JobCompleted += new JobCompletedEventHandler(OnCompleted); } void OnCompleted(object sender, JobCompletedEventArgs e) { string s; Guid taskID = (Guid)e.UserState; switch (s) { case "Success": // Call processResult1(); break; case "Failed": // Call processResult2(); break; default: break; } } public void DoJobHelper() { Object userState = Guid.NewGuid(); ws.DoJob(..., userState); } } (1) I have seen texts on the net on using delegates for callbacks but failed to apply that to my case. All I want to do is to call the appropriate processResult() method upon OnCompleted() event, but dunno how to and where to declare the delegate: public delegate void CallBack(string s); (2) There is a sender object passed in to OnCompleted() but never used, did I miss anything there? Or how can I make good use of sender? Any helps appreciated.

    Read the article

  • Pass Result of ASIHTTPRequest "requestFinished" Back to Originating Method

    - by Intelekshual
    I have a method (getAllTeams:) that initiates an HTTP request using the ASIHTTPRequest library. NSURL *httpURL = [[[NSURL alloc] initWithString:@"/api/teams" relativeToURL:webServiceURL] autorelease]; ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:httpURL] autorelease]; [request setDelegate:self]; [request startAsynchronous]; What I'd like to be able to do is call [WebService getAllTeams] and have it return the results in an NSArray. At the moment, getAllTeams doesn't return anything because the HTTP response is evaluated in the requestFinished: method. Ideally I'd want to be able to call [WebService getAllTeams], wait for the response, and dump it into an NSArray. I don't want to create properties because this is disposable class (meaning it doesn't store any values, just retrieves values), and multiple methods are going to be using the same requestFinished (all of them returning an array). I've read up a bit on delegates, and NSNotifications, but I'm not sure if either of them are the best approach. I found this snippet about implementing callbacks by passing a selector as a parameter, but it didn't pan out (since requestFinished fires independently). Any suggestions? I'd appreciate even just to be pointed in the right direction. NSArray *teams = [[WebService alloc] getAllTeams]; (currently doesn't work, because getAllTeams doesn't return anything, but requestFinished does. I want to get the result of requestFinished and pass it back to getAllTeams:)

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >