2009-06-26 59 views
0

我在我的應用程序中使用單例主幹來處理可疑錯誤。他們將在單身人士內部處理,並在錯誤修復後在整個應用程序中廣播通知。反正這不是我的問題是有關,但是當我通過一個新錯誤的單身對象這樣將協議分配給NSMutableDIctionary?

[[SingletonErrors sharederrors] addError:ErrorDictionary_here]; 

我想ErrorDictionary_here是由給定@protocol在我的代碼保護的NSMutableDictionary所以每當我給我的代碼對我的團隊中的其他人他們會收到關於他們可能忘記傳入字典的錯誤信息的警告。

這甚至可能對於初學者,因爲這是關於增加協議setter和一個getter是更容易喜歡

-(NSMutableArray<myprotocol> *)getmyError{ 

} 

我希望有人能幫助我。

我不是尋求傳遞對象(讀取類實例)而不是字典,而只是應用在我的字典上的協議。

回答

1

如果我明白你在問什麼,你應該能夠做到這一點,沒有太多的麻煩。在你的單例類SingletonErrors中,你應該有:

@interface SingletonErrors : NSObject { 
    // some definitions ... 

    // The current array of all errors. This can also be an NSMutableSet if you like 
    NSMutableArray *sharedErrors; 

    // more definitions ... 
} 

// some properties ... 
@property(nonatomic,retain) NSMutableDictionary<ErrorProtocol> *sharedErrors; 
// more properties ... 

- (void)addError:(NSMutableDictionary<ErrorProtocol> *)newError; 

@end

你應該創建要實現的協議。在這個示例協議中,假設您想提供一種方法來檢查對象是否有效 - 也就是說,該字典包含所有相關信息。

@protocol ErrorProtocol 
- (BOOL)isValid; 
@end

然後您就需要繼承的NSMutableDictionary讓你的類實現了ErrorProtocol協議:

@interface MyMutableDictionary : NSMutableDictionary <ErrorProtocol> { 

} 

@end 

@implementation MyMutableDictionary 

- (BOOL)isValid { 
// Do your validity checking here 

return YES; // Obviously change this line 
} 

@end

然後,當你拋出一個錯誤,你可以在MyMutableDictionary到SingletonErrors一個新的實例傳遞並讓它在MyMutableDictionary上調用isValid選擇器,因爲它確保字典將符合ErrorProtocol並響應isValid

- (void)addError:(NSMutableDictionary<ErrorProtocol> *)newError { 
if([newError isValid]) { 
    // Add the new error to the current array of errors 
    [self.sharedErrors addObject:newError]; 
    // Other code to "broadcast" the error would go here 
} else { 
    // Some code to error out of adding the error would go here 
} 
}

Overall, what this solution does is:

  • Hold a NSMutableArray of all errors in SingletonErrors
  • Each error is an NSMutableDictionary that conforms to ErrorProtocol
  • The object we use for each error is MyMutableDictionary, a subclass of NSMutableDictionary
  • The protocol ErrorProtocol defines a method isValid來檢查錯誤是否是要被添加行
  • 的SingletonErrors對象調用的isValid方法和將誤差適當地
+0

讓我現在就試試看..我以爲這是從來沒有回答的 – 2009-06-26 18:58:36

2

也可以通過像這樣的類別來實現協議:

@interface NSMutableDictionary_TD(ErrorExtensions) <ErrorProtocol> 
@end 

@implementation NSMutableDictionary(ErrorExtensions) 
//implement the ErrorProtocol here 
@end 
1

那是正確的,但犯規感到很高興我..我的解決方案與tim`s合併爲

@implementation NSMutableArray (myAddition) 

- (BOOL)isValid { 
    // Do your validity checking here 

    return YES; // Obviously change this line 
} 
@end 

這節省了代碼的負載..我在血液和fains目標C ..少則更好:) ..謝謝你的答覆反正因爲我確定這個問題不是一個基本的objc問題。它更先進,我認爲大量的人會發現這個話題,並看到修復和你修復100%是正確的,所以感謝你!

我的心是小到存儲我愛到這裏的答覆:)。