好的,我正在使用 Objective-C 编程并使用 Xcode。我已经阅读了 Apple 网站上的文档并了解什么是委托,但是当我谈到如何在代码中实际实现委托方法的部分时,我只是感到困惑,尤其是当他们说“现在实现委托的方法。” 也许只有我一个人,但我不知道在哪里实现该方法(在我只有 ViewController 和 AppDelegate 类的简单情况下,AppDelegate.h/.m 文件是否是正确的位置?)。我想我真正学习的最好方法是看一个非常简单的例子。
我在下面有一些代码,我想知道是否有人可以通过并告诉我如何将委托连接到 ViewController 以显示总和?对不起,如果代码看起来很长,但这是我能想到的最简单的委托示例。为了争论和查看更少的代码(让我更容易看到发生了什么),假设 ServerClass *server 实现了一个服务器,而 ClientClass *client 实现了一个客户端。两者已经相互连接,正在等待输入他们的号码。我记下了我认为正确的内容,但我确定它不完整(就将委托连接到服务器和客户端而言)。我不知道在哪里放的一件事是协议声明,所以如果有人可以请做这个简单的问题,
顺便说一句,如果有人还想向我展示什么连接到什么,我正在使用 iPhone SDK 3.0 的新 GameKit 中的 Peer Picker。例如,我在Peer Picker 的 Apple 指南的第 3 步。现在,我不知道第 5 步在我的项目中的位置。感谢所有可以帮助我理解这个委托实现的人......到目前为止,你们都很棒!
ExampleAppDelegate.h
#import <UIKit/UIKit.h>
@class ExampleAppViewController;
@interface ExampleAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
ExampleAppViewController *viewController;
int sum;
}
@property (nonatomic, retain) sum;
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet ExampleAppViewController *viewController;
-(void) addNum:(int)num;
@end
ExampleAppDelegate.m
#import "ExampleAppDelegate.h"
#import "ExampleAppViewController.h"
@implementation ExampleAppDelegate
@synthesize window;
@synthesize viewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
application.idleTimerDisabled = YES;
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
-(void)addNum:(int)num {
sum += num;
}
@end
ExampleAppViewController.h
#import <UIKit/UIKit.h>
#import <GameKit/GameKit.h>
@interface ExampleAppViewcontroller : NSObject {
IBOutlet UILabel *sumField; // will display the total sum, one number entered //by the server and one entered by the client, on both iPhones after calculation
int sum; // the total sum after addition;
ServerClass *server; // some server
ClientClass *client; // some client
int num; // the number to add to sum
}
@property(nonatomic, assign) sum;
@property(nonatomic, retain) num;
-(void) displaySum;
@end
ExampleAppViewController.m
#import "ExampleAppViewcontroller.h"
@implementation ExampleAppViewController
@synthesize sum;
@synthesize num;
-(void) displaySum {
[sumfield setText: @"%i", sum];
}
@end