How do I know which object is asking the delegate for information?

瘦欲@ 提交于 2019-12-12 02:28:58

问题


In my design, choosers tell an app controller how many items, and of which color, the user would like to see in each of two Views. I have a single NSView object description (myView.h, myView.m) which the controller instantiates twice. When the user adjusts a chooser to change, say, the number of items to be drawn in viewOne, the App Controller updates its local variable for this qty, and tells viewOne to redraw itself. As part of redrawing itself, viewOne needs to ask the delegate (App Controller) how many items to draw. When this happens via the protocol, by what mechanism does the delegate know that it is viewOne who is asking for the qty variable? i.e. how does the delegate know which variable to respond with?


回答1:


The first argument to a delegate/data source call is, by convention, the object which is delegating, e.g.:

- (void)applicationDidFinishLaunching:(NSApplication *)app;
- (NSTableRowView *)tableView:(NSTableView *)tableView
                rowViewForRow:(NSInteger)row;

Inside these methods, app and tableView will be the requesters.

You should write your own delegate protocols to follow this pattern.

More in the "Delegates and Data Sources" chapter of Apple's Concepts in Objective-C, although strictly this has nothing to do with the language itself: it's a pattern from the Cocoa (Touch) framework.




回答2:


I figured out that I can (not sure if I should) use isEqual: in the delegate's routine, to determine which object called:

- (int)numberOfItemsInTheView:(myView *)aView {
    int itemCount = 0;

    if([aView isEqual:[self viewOne]]) {
        itemCount = 5;
    } else if([aView isEqual:[self viewTwo]]) {
        itemCount = 18;
    }
    return itemCount;
}

It is the isEqual portion/statement that I was not aware of or understanding. Regarding Josh's answer, I can see that I may not fully understand the implications and/or requirements (conventions?) of the protocol/delegate coding structure.



来源:https://stackoverflow.com/questions/33658398/how-do-i-know-which-object-is-asking-the-delegate-for-information

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!