Мало перепутанный на Делегатах в Objective C

Это не объект WPF, а стандартный XML, один и BtBh правильно ответили, что это, x относится к пространству имен по умолчанию. В XML, когда Вы не снабжаете префиксом элемент/атрибут пространство имен, это предполагает желание пространства имен по умолчанию. Так ввод всего Name является не чем иным как стенографией для x:Name. Больше деталей о пространствах имен XML может быть найдено в текст ссылки

12
задан Alex Rozanski 28 August 2009 в 22:40
поделиться

4 ответа

Think of delegates as inversion the direction of dependencies. In most frameworks the clients will inject the required dependencies into instances, usually in the constructor or by setters.

Cocoa does the reverse; instances instead request the data when and if it is needed.

There are four main types of delegate methods:

  • Conditionally before - Signals something is about to happen, but the delegate may abort. Name always include the word Should.
    Example: searchBarShouldEndEditing:.
  • Unconditionally before - Signals something is about to happen. Name always include the word will.
    Example: applicationWillTerminate:.
  • Unconditionally after - Signals something has happened. Name always include the word did.
    Example: applicationDidFinishLaunching:.
  • Customizers - Request information for how to function. Name includes the information that is required.
    Example tableView:viewForHeaderInSection:.

All delegate methods always have their sender as one of the arguments. Any delegate method may have a return value that alters how the sender behaves.

20
ответ дан 2 December 2019 в 04:17
поделиться

Let's say you want to present the user with an alert, and you want a method to run when the user touches one of the buttons. The problem is, how do you know what method to call, on which object, when someone touches a button?

In order for a class to be a delegate, you have to declare it as such. In the above example, lets say you have an ApplicationController object which controls the flow of your application. In the declaration, we would say

@interface ApplicationController : NSObject <UIAlertViewDelegate>

This tells the compiler that ApplicationController is going to implement some methods in the UIAlertViewDelegate protocol. We look that protocol up in our documentation, and see a list of methods. As we want to do something when a button is pressed, we see:

alertView:clickedButtonAtIndex: - Sent to the delegate when the user clicks a button on an alert view. This method is optional.

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

So, if we implement a method in ApplicationController called alertView:clickedButtonAtIndex, create an ApplicationController object, and then set that object as the delegate of an alert we show, everything is set up. As soon as someone presses a button on the alert, the alertView:clickedButtonAtIndex method will be called, passing in the alertView and the index of the button pressed.

This allows you to do whatever you want with that information. A simple case statement:

if( buttonIndex == 0 ) {
    _myString = @"Pressed the button";
} else {
    _myString = @"Pressed the other button";
}

The Objective-C reference docs are very, very good, and all the delegate protocols are pretty self explanatory.

7
ответ дан 2 December 2019 в 04:17
поделиться

Хороший способ понять делегатов - это пример. Одним из примеров является UITableView (или NSTableView , в зависимости от того, говорим ли мы об iPhone или Mac OS). В любом случае табличное представление имеет делегат и dataSource (оба действуют как вспомогательные объекты для получателя).

Вместо обработки UITableView события, когда, например, пользователь нажимает одну из его строк, вместо этого он сообщает своему делегату «Эй! Я нажимал на эту строку и этот раздел, делайте, что хотите!». Обычно делегат представляет собой какой-то контроллер, который реализует правильный метод. Таким образом, табличное представление (после проверки того, действительно ли делегат имеет определение для метода) отправляет сообщение, подобное этому:

[delegate tableView:self didSelectRowAtIndexPath:indexPath];

Поскольку ваш контроллер является делегатом таблицы и реализует этот метод, он решает, что делать. Когда метод завершается (в этом случае он должен просто вернуть void ), выполнение продолжается в табличном представлении.

Делегаты - это концепция. Это не языковая функция Objective-C. Член делегата UITableView похож на любой другой объект. Хотя делегаты обычно не сохраняются, они вместо этого назначаются (чтобы избежать циклов сохранения ).

Они очень удобны, когда вы разбираетесь в них. Я предлагаю попрактиковаться с такими примерами, как TableViews ( NSTableView , как я сказал ранее,

6
ответ дан 2 December 2019 в 04:17
поделиться

Взгляните на мой учебник по шаблону проектирования делегата здесь: http://www.jonmsterling.com/blog/?p=74 . Надеюсь, это поможет.

0
ответ дан 2 December 2019 в 04:17
поделиться
Другие вопросы по тегам:

Похожие вопросы: