2012-03-19 82 views
1

這應該是一個簡單的問題 - 但我很難搞清楚。我試圖在一個對象上創建一個屬性,這樣在prepareForSegue期間,我可以告訴對象它的委託是什麼。我知道我可以通過協議來做到這一點,但我認爲這種情況下直接的做法是最簡單的。不幸的是,下面的代碼會導致一個編譯器錯誤:聲明委託屬性時出錯

#import <UIKit/UIKit.h> 
#import "PlanningViewController.h" 

@interface DepartmentViewController : UITableViewController 

@property (nonatomic, weak) PlanningViewController *planningDelegate; 

@end 

當我鍵入財產申報時,Xcode識別PlanningViewController甚至顯示文本,我只是通過TAB。但編譯器卻抱怨道:

Unknown type name 'PlanningViewController': did you mean 'UISplitViewController'? 

我在做什麼錯?

PlanningViewController.h看起來是這樣的:

#import <UIKit/UIKit.h> 
#import "DepartmentViewController.h" 

@interface PlanningViewController : UITableViewController 


// Table cell connections 
- (IBAction)addItemPressed:(id)sender; 


@end 
+1

請顯示'PlanningViewController.h'的內容。 – trojanfoe 2012-03-19 13:39:42

回答

1

刪除此行從您的PlanningViewController.h頭文件:

#import "DepartmentViewController.h" 

你有一個循環在你的頭文件的東西。

更妙的是,使DepartmentViewController.h這個樣子的(沒有必要包括在PlanningViewController.h頭文件):

#import <UIKit/UIKit.h> 

@class PlanningViewController; 

@interface DepartmentViewController : UITableViewController 

@property (nonatomic, weak) PlanningViewController *planningDelegate; 

@end 
+0

做過這份工作。謝謝! – CodeBuddy 2012-03-19 13:53:49

+0

@CodeBuddy就是這樣 - 歡呼! – trojanfoe 2012-03-25 14:34:54

0

我想你已經有種錯過了代表圖案的要點之一這是解耦你的對象。聲明此委託的最好的辦法是:

#import <UIKit/UIKit.h> 

@protocol DepartmentViewControllerDelegate; // forward declaration of protocol 

@interface DepartmentViewController : UITableViewController 

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

@end 

@protocol DepartmentViewControllerDelegate 
- (void)departmentViewController:(DepartmentViewController *)controller 
       isProcessingPeople:(NSArray *)people 
@end 

在你的部門的視圖控制器,你會那麼寫是這樣的:

if ([self.delegate respondsToSelector:@selector(departmentViewController:isProcessingPeople:)]) { 
    [self.delegate departmentViewController:self isProcessingPeople:people]; 
} 

並在您的規劃視圖控制器,你會實現這個方法:

- (void)departmentViewController:(DepartmentViewController *)controller 
       isProcessingPeople:(NSArray *)people { 
    // do necessary work here 
} 

這裏的例子只是一個可以發送給委託的消息的例子。你可以添加你需要的任何東西,但是這樣做會使你的控制器之間沒有耦合。計劃視圖控制器知道需要的關於部門控制器的所有內容,但部門控制器不需要知道計劃控制器的任何信息。

如果你想堅持你現在擁有的東西,只要認識到它不是真正的委託模式,你應該重新命名你的財產。

+0

有道理。我堅持使用它,但是,正如你所建議的那樣,爲了避免混淆,請重新命名。 – CodeBuddy 2012-03-25 14:11:27