好吧,我正在編程Objective-C和使用Xcode。我已閱讀了Apple網站上的文檔,瞭解代理的內容,但是當我談到如何將代理方法實際實現爲代碼時,我只是感到困惑,特別是當他們說「像現在實現代理方法。」也許這只是我,但我不知道確切的WHERE實現方法(在我只有ViewController和AppDelegate類的簡單情況下,AppDelegate.h/.m文件是否是正確的位置?)。我想我真正想學習的最好方法就是看一個非常簡單的例子。簡單代表示例?
我在下面有一些代碼,我想知道如果有人可以通過並告訴我如何將委託連接到ViewController,以便它顯示總和?對不起,如果代碼看起來很長,但這是我能想到的最簡單的代表性例子。爲了爭論和少看代碼(使我更容易看到發生的事情),可以說ServerClass *服務器實現了一個服務器,而ClientClass *客戶端實現了一個客戶端。兩者已經相互連接並等待輸入他們的號碼。我放下了我認爲正確的東西,但我確信它不完整(只要將代理連接到服務器和客戶端)。有一件事我不知道該把協議聲明放在哪裏,所以如果有人可以請做這個簡單的問題,那麼就可以瞭解一個委託如何實現到一個類中。
順便說一下,我正在與iPhone Picker的新GameKit中的Peer Picker合作,如果有人也想告訴我什麼是連接到什麼的。例如,我在step 3 of the Apple guide for Peer Picker。現在,我不知道步驟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
如果在我的代碼中的一些語法問題的話,那是因爲我現在不是在我的Mac,我必須鍵入了一個基於Windows的PC上。 – 2009-06-27 01:06:54
我讀過關於語法的評論,但如果你不知道,我相信你不需要(非原子,保留)一個整數。據我所知,我可能是錯的,我從我見過的代碼的基礎上,以及你不保留整數的事實作爲基礎。只要做@property總和; – 2009-06-27 02:04:45
我認爲首選的物業組合是@property(非原子,分配)的事情是不是對象的指針(整數,布爾值將等) – Tim 2009-06-27 03:09:35