How do I create delegates in Objective-C?

后端 未结 19 2570
一整个雨季
一整个雨季 2020-11-21 04:48

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

But how do I create them?

19条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 05:25

    Ok, this is not really an answer to the question, but if you are looking up how to make your own delegate maybe something far simpler could be a better answer for you.

    I hardly implement my delegates because I rarely need. I can have ONLY ONE delegate for a delegate object. So if you want your delegate for one way communication/passing data than you are much better of with notifications.

    NSNotification can pass objects to more than one recipients and it is very easy to use. It works like this:

    MyClass.m file should look like this

    #import "MyClass.h"
    @implementation MyClass 
    
    - (void) myMethodToDoStuff {
    //this will post a notification with myClassData (NSArray in this case)  in its userInfo dict and self as an object
    [[NSNotificationCenter defaultCenter] postNotificationName:@"myClassUpdatedData"
                                                        object:self
                                                      userInfo:[NSDictionary dictionaryWithObject:selectedLocation[@"myClassData"] forKey:@"myClassData"]];
    }
    @end
    

    To use your notification in another classes: Add class as an observer:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(otherClassUpdatedItsData:) name:@"myClassUpdatedData" object:nil];
    

    Implement the selector:

    - (void) otherClassUpdatedItsData:(NSNotification *)note {
        NSLog(@"*** Other class updated its data ***");
        MyClass *otherClass = [note object];  //the object itself, you can call back any selector if you want
        NSArray *otherClassData = [note userInfo][@"myClassData"]; //get myClass data object and do whatever you want with it
    }
    

    Don't forget to remove your class as an observer if

    - (void)dealloc
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    

提交回复
热议问题