2013-01-01 92 views
0

我是相當新的編程(我對編程沒有教育 - 我知道一切已被閱讀教程獲得),並在Xcode和iOS的開發全新。到目前爲止,我理解開發iOS應用程序的基礎知識,但有一點我無法弄清楚代表作品是如何工作的。我理解使用委託背後的想法,但我不知道我在嘗試實現委託時做了什麼錯誤。我創建了一個小例子(單視圖應用程序)來說明我如何實現自定義委託,並希望您能告訴我我做錯了什麼。我使用的XCode 4.5.2定製代表有麻煩

,iOS6.0與ARC啓用。

在這個例子中我建立一個簡單的NSObject的子類(TestClassWithDelegate)。 TestClassWithDelegate.h看起來是這樣的:

@protocol TestDelegate <NSObject> 

-(void)stringToWrite:(NSString *)aString; 

@end 

@interface TestClassWithDelegate : NSObject 

@property (weak, nonatomic) id<TestDelegate> delegate; 

-(TestClassWithDelegate *)initWithString:(NSString *)theString; 

@end 

TestClassWithDelegate.m看起來是這樣的:

#import "TestClassWithDelegate.h" 

@implementation TestClassWithDelegate 

@synthesize delegate; 

-(TestClassWithDelegate *)initWithString:(NSString *)theString 
{ 
    self=[super init]; 

    [delegate stringToWrite:theString]; 

    return self; 
} 

@end 

視圖控制器(視圖控制器)由一個UILabel,我想寫一些文字的。 ViewController.h看起來是這樣的:

#import "TestClassWithDelegate.h" 

@interface ViewController : UIViewController <TestDelegate> 

@property (weak, nonatomic) IBOutlet UILabel *testlabel; 

@end 

ViewController.m看起來是這樣的:

#import "ViewController.h" 

@interface ViewController() 

@end 

@implementation ViewController 

@synthesize testlabel; 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    self.testlabel.text = @"Before delegate"; 
    TestClassWithDelegate *dummy = [[TestClassWithDelegate alloc] initWithString:@"AfterDelegate"]; //This should init the TestClassWithDelegate which should "trigger" the stringToWrite method. 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

#pragma mark Test delegate 
- (void)stringToWrite:(NSString *)aString 
{ 
    self.testlabel.text = aString; 
} 
@end 

問題與上面的例子是,在視圖中的標籤只寫「委託之前」,我想它編寫「AfterDelegate」。

非常感謝所有幫助。新年快樂。

回答

4

您沒有設置委託的任何地方,所以這將是nil。你需要initWithString:delegate:而不是initWithString:或者(更好)只需創建對象,設置委託並單獨發送字符串。

您可能犯了一個(常見)錯誤,您認爲@synthesize實際上會在您的代碼中創建一個對象併爲其分配一個值。它不是。這是一個(現在主要是多餘的!)指令給編譯器來爲屬性創建訪問器方法。

下面是你的委託類的略微重新設計例子,一些示例用法:

.h文件中:

@interface TestClassWithDelegate : NSObject 

@property (weak, nonatomic) id<TestDelegate> delegate; 
-(void)processString:(NSString*)string 

@end 

.m文件:

@implementation TestClassWithDelegate 

-(void)processString:(NSString *)theString 
{ 
    [delegate stringToWrite:theString]; 
} 

@end 

用法:

TestClassWithDelegate *test = [TestClassWithDelegate new]; 
[test processString:@"Hello!"]; // Nothing will happen, there is no delegate 
test.delegate = self; 
[test processString:@"Hello!"]; // Delegate method will be called. 
+0

非常感謝您的曲ick回覆。問題中的例子是我很快創建的(它仍然捕捉了我的問題的理解,瞭解委託人的工作方式)。在我實現了 .delegate = self之後,它解決了我在其他項目中的問題。 –