Skip to content

Instantly share code, notes, and snippets.

@vc7
Last active August 29, 2015 14:08
Show Gist options
  • Select an option

  • Save vc7/7ffaf593548708cccc19 to your computer and use it in GitHub Desktop.

Select an option

Save vc7/7ffaf593548708cccc19 to your computer and use it in GitHub Desktop.
check isbn in objc
#pragma mark - ISBN Logic
- (BOOL)checkISBN:(NSString *)ISBN error:(NSError * __autoreleasing *)error
{
if (ISBN.length != 10 || ISBN.length != 13) {
NSInteger checkSum = 0;
NSInteger length = ISBN.length;
if (length == 10) {
// !!!: 10
NSInteger modulo = 11;
NSInteger checkDigit = [[ISBN substringWithRange:NSMakeRange(length - 1, 1)] integerValue];
for (NSInteger index = 0; index < length - 1; index ++) {
NSInteger digit = [[ISBN substringWithRange:NSMakeRange(index, 1)] integerValue];
checkSum += digit * (index + 1);
}
if (checkSum % modulo == checkDigit) {
return YES;
} else {
if (error) {
*error = [NSError errorWithDomain:@"tw.com.springhouse.klife" code:1 userInfo:@{NSLocalizedDescriptionKey:@"The checkSum of ISBN-10 did not pass."}];
}
return NO;
}
} else {
// !!!: 13
NSInteger modulo = 10;
NSInteger checkDigit = [[ISBN substringWithRange:NSMakeRange(length - 1, 1)] integerValue];
for (NSInteger index = 0; index < length - 1; index ++) {
NSInteger digit = [[ISBN substringWithRange:NSMakeRange(index, 1)] integerValue];
if (index % 2) {
checkSum += digit * 3;
} else {
checkSum += digit * 1;
}
}
if (modulo - (checkSum % modulo) == checkDigit) {
return YES;
} else {
if (error) {
*error = [NSError errorWithDomain:@"tw.com.springhouse.klife" code:2 userInfo:@{NSLocalizedDescriptionKey:@"The checkSum of ISBN-13 did not pass."}];
}
return NO;
}
}
} else {
if (error) {
*error = [NSError errorWithDomain:@"tw.com.springhouse.klife" code:3 userInfo:@{NSLocalizedDescriptionKey:@"The length of ISBN should be 10 or 13 digits."}];
}
return NO;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment