Objective c 如何在目标C中创建委托人?
我试图学习如何在目标C中实施委托模式。但讨论几乎完全集中在协议的采用,然后实施特定协议附带的委托方法,或者单独的委托原则,或者单独的协议 我找不到的是一个简单易懂的材料,关于如何编写一个充当委托人的类。我指的是类,某个事件的消息将来自该类,该类将提供接收该消息的协议,类似于2in1描述。(议定书和授权) 为了便于学习,我想使用以下简单示例,使用iPhone、Cocoa touch应用程序和Xcode4.2,使用ARC,不使用故事板或笔尖 让我们有一个名为“Delegator”的类,它是NSObject的一个子类。Delegator类具有名为“report”的NSString实例变量,并采用UIAccelerometerDelegate协议。在Delegator实现中,我将实现delegate方法Objective c 如何在目标C中创建委托人?,objective-c,cocoa-touch,delegates,Objective C,Cocoa Touch,Delegates,我试图学习如何在目标C中实施委托模式。但讨论几乎完全集中在协议的采用,然后实施特定协议附带的委托方法,或者单独的委托原则,或者单独的协议 我找不到的是一个简单易懂的材料,关于如何编写一个充当委托人的类。我指的是类,某个事件的消息将来自该类,该类将提供接收该消息的协议,类似于2in1描述。(议定书和授权) 为了便于学习,我想使用以下简单示例,使用iPhone、Cocoa touch应用程序和Xcode4.2,使用ARC,不使用故事板或笔尖 让我们有一个名为“Delegator”的类,它是NSObj
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
此委托方法将创建NSString@“myReport”,并在任何时候发生加速计事件时将其存储在报告变量中。此外,我希望有第二个名为ReportsStorage的类(NSobject的子类),它可以在名为latestReport的实例变量中存储一些Nsstring(report)。
到现在为止,一直都还不错。
现在让我们回到Delegator类。我想在名为ReportsDelegate的Delegator中实现一个协议,该协议将通知采用它的类(ReportsStorage类),报告已生成,并将通过委托方法传递该报告,委托方法(我相信)应该是这样的
-(void)delegator:(Delegator *)delegator didCreateNewReport:(NSString *)report;
您能否提供Delegator类(包括“delegate”属性)的代码,并说明每行代码的含义
提前感谢,您需要将委托属性声明为
id
类型。也就是说,符合ReportsDelegate协议(
)的任何对象类型(id
)。然后,如果委托方法被认为是可选的,请在调用它之前检查委托是否响应该选择器。(响应选择器:
)
像这样:
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