Objective C의 iPhone 개발에서 "대리자"는 무엇입니까?
이 질문에 이미 답변이 있습니다.
Objective C의 iPhone 개발에서 "대리자"는 무엇입니까?
이 토론 보기
대리자는 이벤트가 발생할 때 한 개체가 다른 개체에 메시지를 보낼 수 있도록합니다. 예를 들어 NSURLConnection 클래스를 사용하여 웹 사이트에서 비동기 적으로 데이터를 다운로드하는 경우 입니다. NSURLConnection에는 세 가지 공통 대리자가 있습니다.
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
NSURLConnection이 실패하거나 성공적으로 완료되거나 웹 사이트에서 응답을 받으면 이러한 델리게이트 중 하나 이상이 호출됩니다.
대리자는 대리자 보유자가 호출하는 방법을 알고있는 메서드 집합이있는 개체에 대한 포인터입니다. 즉, 나중에 생성 된 객체에서 특정 콜백을 활성화하는 메커니즘 입니다.
좋은 예이다UIAlertView
. 사용자 UIAlertView
에게 짧은 메시지 상자를 표시 하는 개체를 만들어 "확인"및 "취소"와 같은 두 개의 단추를 선택할 수 있습니다. 에 UIAlertView
다시 전화를 걸 수있는 방법 이 필요하지만 어떤 개체를 다시 호출하고 어떤 메서드를 호출할지에 대한 정보가 없습니다.
이 문제를 해결하기 위해, 당신은 보낼 수있는 self
포인터를 UIAlertView
(선언에 의해 위임 개체로, 교환에 당신은 동의하는 UIAlertViewDelegate
몇 가지 방법을 구현하는 개체의 헤더 파일을) UIAlertView
과 같은 호출 할 수 있습니다를, alertView:clickedButtonAtIndex:
.
대리자 디자인 패턴 및 기타 콜백 기술 에 대한 간략한 소개를 보려면 이 게시물 을 확인하십시오 .
참조 :
델리게이트는 디자인 패턴입니다. 특별한 구문이나 언어 지원이 없습니다.
대리자는 특정 상황이 발생할 때 다른 개체가 메시지를 보내는 개체 일 뿐이므로 대리자는 원래 개체가 설계되지 않은 앱별 세부 정보를 처리 할 수 있습니다. 서브 클래 싱없이 동작을 사용자 정의하는 방법입니다.
이 Wikipedia 기사가 가장 잘 설명한다고 생각합니다. http://en.wikipedia.org/wiki/Delegation_pattern
디자인 패턴의 "단지"구현이며 Objective-C에서 매우 일반적입니다.
간단한 프로그램을 통해 정교 해보려고합니다
두 클래스
Student.h
#import <Foundation/Foundation.h>
@interface Student : NSObject
@property (weak) id delegate;
- (void) studentInfo;
@end
Student.m
#import "Student.h"
@implementation Student
- (void) studentInfo
{
NSString *teacherName;
if ([self.delegate respondsToSelector:@selector(teacherName)]) {
teacherName = [self.delegate performSelector:@selector(teacherName)];
}
NSLog(@"\n Student name is XYZ\n Teacher name is %@",teacherName);
}
@end
Teacher.h
#import <Foundation/Foundation.h>
#import "Student.h>
@interface Teacher: NSObject
@property (strong,nonatomic) Student *student;
- (NSString *) teacherName;
- (id) initWithStudent:(Student *)student;
@end
Teacher.m
#import "Teacher.h"
@implementation Teacher
- (NSString *) teacherName
{
return @"ABC";
}
- (id) initWithStudent:(Student *)student
{
self = [ super init];
if (self) {
self.student = student;
self.student.delegate = self;
}
return self;
}
@end
main.m
#import <Foundation/Foundation.h>
#import "Teacher.h"
int main ( int argc, const char* argv[])
{
@autoreleasepool {
Student *student = [[Student alloc] init];
Teacher *teacher = [[Teacher alloc] initWithStudent:student];
[student studentInfo];
}
return 0;
}
설명 :::
메인 메소드에서 언제
initWithStudent:student
실행할지1.1 교사의 개체 속성 ' student '가 학생 개체와 함께 할당됩니다.
1.2
self.student.delegate = self
means student object's delegate will points to teacher object
[student studentInfo]
호출 될 때 주 메서드에서2.1
[self.delegate respondToSelector:@selector(teacherName)]
여기서 델리게이트는 이미 Teacher 객체를 가리 키므로 'teacherName'인스턴스 메서드를 호출 할 수 있습니다.2.2 그래서
[self.delegate performSelector:@selector(teacherName)]
쉽게 실행됩니다.
Teacher 개체가 자신의 메서드를 호출하기 위해 학생 개체에 대리자를 할당하는 것처럼 보입니다.
' teacherName '메소드 라는 학생 객체를 볼 수있는 상대적인 아이디어 이지만 기본적으로 교사 객체 자체에 의해 수행됩니다.
부디! iOS에서 대리인이 어떻게 작동하는지 이해하려면 아래의 간단한 단계별 자습서를 확인하십시오.
두 개의 ViewController를 만들었습니다 (데이터를 다른 곳으로 보내기 위해)
- FirstViewController는 델리게이트 (데이터 제공)를 구현합니다.
- SecondViewController는 (데이터를받을) 델리게이트를 선언합니다.
다음은 도움이 될 수있는 샘플 코드입니다.
AppDelegate.h
#import <UIKit/UIKit.h>
@class FirstViewController;
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) FirstViewController *firstViewController;
@end
AppDelegate.m
#import "AppDelegate.h"
#import "FirstViewController.h"
@implementation AppDelegate
@synthesize firstViewController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
//create instance of FirstViewController
firstViewController = [[FirstViewController alloc] init];
//create UINavigationController instance using firstViewController
UINavigationController *firstView = [[UINavigationController alloc] initWithRootViewController:firstViewController];
//added navigation controller to window as a rootViewController
self.window.rootViewController = firstView;
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
FirstViewController.h
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
@interface FirstViewController : UIViewController<MyDelegate>
@property (nonatomic, retain) NSString *mesasgeData;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UIButton *nextButton;
- (IBAction)buttonPressed:(id)sender;
@property (nonatomic, strong) SecondViewController *secondViewController;
@end
FirstViewController.m
#import "FirstViewController.h"
@interface FirstViewController ()
@end
@implementation FirstViewController
@synthesize mesasgeData;
@synthesize textField;
@synthesize secondViewController;
#pragma mark - View Controller's Life Cycle methods
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - Button Click event handling method
- (IBAction)buttonPressed:(id)sender {
//get the input data from text feild and store into string
mesasgeData = textField.text;
//go keypad back when button clicked from textfield
[textField resignFirstResponder];
//crating instance of second view controller
secondViewController = [[SecondViewController alloc]init];
//it says SecondViewController is implementing MyDelegate
secondViewController.myDelegate = self;
//loading new view via navigation controller
[self.navigationController pushViewController:secondViewController animated:YES];
}
#pragma mark - MyDelegate's method implementation
-(NSString *) getMessageString{
return mesasgeData;
}
@end
SecondViewController.h
//declare our own delegate
@protocol MyDelegate <NSObject>
-(NSString *) getMessageString;
@end
#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *messageLabel;
@property (nonatomic, retain) id <MyDelegate> myDelegate;
@end
SecondViewController.m
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
@synthesize messageLabel;
@synthesize myDelegate;
- (void)viewDidLoad
{
[super viewDidLoad];
messageLabel.text = [myDelegate getMessageString];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end
델리게이트를 이해하면이 모든 답변이 의미가 있다고 생각합니다. 개인적으로 저는 C / C ++의 땅에서 왔고 Fortran 등과 같은 절차 적 언어 이전에 왔으므로 C ++ 패러다임에서 유사한 아날로그를 찾는 데 2 분 정도 걸립니다.
C ++ / Java 프로그래머에게 델리게이트를 설명한다면
What are delegates ? These are static pointers to classes within another class. Once you assign a pointer, you can call functions/methods in that class. Hence some functions of your class are "delegated" (In C++ world - pointer to by a class object pointer) to another class.
What are protocols ? Conceptually it serves as similar purpose as to the header file of the class you are assigning as a delegate class. A protocol is a explicit way of defining what methods needs to be implemented in the class who's pointer was set as a delegate within a class.
How can I do something similar in C++? If you tried to do this in C++, you would by defining pointers to classes (objects) in the class definition and then wiring them up to other classes that will provide additional functions as delegates to your base class. But this wiring needs to be maitained within the code and will be clumsy and error prone. Objective C just assumes that programmers are not best at maintaining this decipline and provides compiler restrictions to enforce a clean implementation.
The delegate fires the automatic events in Objects C. If you set the delegate to Object, it sends the message to another object through the delegate methods.
It's a way to modify the behavior of a class without requiring subclassing.
Each Objects having the delegate methods.These delegate methods fires, when the particular Objects take part in user interaction and Program flow cycle.
Simply stated: delegation is a way of allowing objects to interact with each other without creating strong interdependencies between them.
A delegate captures the taping actions of an user and performs particular Action according to the user Taping Action.
Delegate is nothing but instance of Object which we can call methods behalf of that Objects. and also helps to create methods in rumtime of that Objects.
참고URL : https://stackoverflow.com/questions/2534094/what-is-a-delegate-in-objective-cs-iphone-development
'Development Tip' 카테고리의 다른 글
C에서 OO 스타일 다형성을 어떻게 시뮬레이션 할 수 있습니까? (0) | 2020.11.03 |
---|---|
Django 사용자 정의 템플릿 태그의 액세스 요청 (0) | 2020.11.03 |
Android 레이아웃 오른쪽 정렬 (0) | 2020.11.03 |
자바 "?" (0) | 2020.11.03 |
SQL Server-부울 리터럴? (0) | 2020.11.03 |