Last active
August 29, 2015 14:08
-
-
Save vc7/7ffaf593548708cccc19 to your computer and use it in GitHub Desktop.
check isbn in objc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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