假設你的屬性是鍵 - 值兼容,你也應該實現鍵值兼容驗證程序(因爲如果你使用@synthesize他們會)。看看蘋果關於此事的文檔:http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueCoding/Concepts/Validation.html
重要的是要注意的是,驗證不會自動發生,除非使用某種綁定。您可以直接致電驗證人或致電validateValue:forKey:error:
。
您可以重寫生成的setter在保存之前調用驗證器,但如果您使用的是綁定,則可能不是您想要執行的操作,因爲驗證器可能會多次調用一次。
另請注意,驗證器可能會更改正在驗證的值。
因此,讓我們看看你的例子(未經測試,順便說一句。我不是Mac附近):
@implementation MyClass
@synthesize myValue;
-(BOOL)validateMyValue:(id *)ioValue error:(NSError **)outError
{
if (*ioValue == nil) {
// trap this in setNilValueForKey
// alternative might be to create new NSNumber with value 0 here
return YES;
}
if ([*ioValue intValue] < 0) {
NSString *errorString = @"myValue must be greater than zero";
NSDictionary *userInfoDict = [NSDictionary dictionaryWithObject:errorString
forKey:NSLocalizedDescriptionKey];
NSError *error = [[[NSError alloc] initWithDomain:@"MyValueError"
code:0
userInfo:userInfoDict] autorelease];
*outError = error;
return NO;
} else {
return YES;
}
}
如果你想覆蓋合成setter和利用它做些驗證(還未經測試):
- (void)setMyValue:(int)value {
id newValue = [NSNumber numberWithInt:value];
NSError *errorInfo = nil;
if ([self validateMyValue:&newValue error:&errorInfo]) {
myValue = [newValue intValue];
}
}
你可以看到,我們不得不包裹在NSNumber實例中的整數來做到這一點。
這可能值得用'cocoa'和'macosx'來標記。我沒有足夠的聲譽。 – toholio 2009-06-12 04:52:25