2011-12-12 77 views
2

我想知道如何在目标C中实现委托模式。但讨论几乎完全集中在协议的采用,然后实现代表方法,这些委托方法带有特定的协议 - 或 - 委托原则 - 或单独的协议。如何在目标C中创建委托人?

我无法找到的是一个关于如何编写将作为委托人的类的简单易懂的材料。我的意思是这个班级,其中一些事件的信息将来自哪一类,并提供用于接收该信息的协议 - 这种类型的2in1描述。 (协议和委托)。为了我的学习目的,我想使用一个iPhone,一个Cocoa touch应用程序和Xcode4.2,使用ARC,不使用Storyboard或NIBs,去学习下面的例子。

让我们来创建一个名为“Delegator”的类,它是NSObject的一个子类。对被代理类已NSString的实例变量命名为“报告”,并采用UIAccelerometerDelegate protocol.In委托人实现,我将实现委托方法

-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration 

此委托方法将创建一个的NSString @“myReport”,并将其存储在报告变量中,任何时候都有一个加速度计事件。此外,我想要第二个名为ReportsStorage的类(NSobject的子类),它可以在其实例变量lastReport中存储一些Nsstring(报告)。 目前为止这么好。 现在让我们回到Delegator类。我想在Delegator中实现一个名为ReportsDelegate的协议,它将通知采用它的类(ReportsStorage类),报告已生成并将通过委托方法传递此报告,这应该是(我相信)类似于这

-(void)delegator:(Delegator *)delegator didCreateNewReport:(NSString *)report; 

能否请您为委托者类(包括在“委托”属性)的代码,将做到这一点,有着怎样的每一行代码句话的含义?

由于提前,EarlGrey

+0

可能重复[如何在Objective-C的委托的工作?( http://stackoverflow.com/questions/1045803/how-does-a-delegate-work-in-objective-c) – vikingosegundo

回答

3

你需要委托财产申报作为id<ReportsDelegate>类型。也就是说,符合ReportsDelegate协议(<ReportsDelegate>)的任何对象类型(id)。然后,如果委托方法被认为是可选的,请检查委托在调用之前是否响应该选择器。 (respondsToSelector:)。

像这样:

Delegator.h

#import <Foundation/Foundation.h> 

// Provide a forward declaration of the "Delegator" class, so that we can use 
// the class name in the protocol declaration. 
@class Delegator; 

// Declare a new protocol named ReportsDelegate, with a single optional method. 
// This protocol conforms to the <NSObject> protocol 
@protocol ReportsDelegate <NSObject> 
@optional 
-(void)delegator:(Delegator *)delegator didCreateNewReport:(NSString *)report; 
@end 

// Declare the actual Delegator class, which has a single property called 'delegate' 
// The 'delegate' property is of any object type, so long as it conforms to the 
// 'ReportsDelegate' protocol 
@interface Delegator : NSObject 
@property (weak) id<ReportsDelegate> delegate; 
@end 

Delegator.m

#import "Delegator.h" 

@implementation Delegator 
@synthesize delegate; 

// Override -init, etc. as needed here. 

- (void)generateNewReportWithData:(NSDictionary *)someData { 

    // Obviously, your report generation is likely more complex than this. 
    // But for purposes of an example, this works. 
    NSString *theNewReport = [someData description]; 

    // Since our delegate method is declared as optional, check whether the delegate 
    // implements it before blindly calling the method. 
    if ([self.delegate respondsToSelector:@selector(delegator:didCreateNewReport:)]) { 
     [self.delegate delegator:self didCreateNewReport:theNewReport]; 
    } 
} 

@end 
+0

我们不需要综合de Delegator.m中的legate属性? –

+0

哦,我们绝对会。我会解决这个问题。谢谢。 –

+0

玩了几个小时后,我明白了一切,这要归功于你的描述。非常感谢 :)。 –