如果我明白你在問什麼,你應該能夠做到這一點,沒有太多的麻煩。在你的單例類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方法和將誤差適當地
來源
2009-06-26 17:57:49
Tim
讓我現在就試試看..我以爲這是從來沒有回答的 – 2009-06-26 18:58:36