Created
June 24, 2013 07:31
-
-
Save Abeansits/5848341 to your computer and use it in GitHub Desktop.
A utility box for NSStrings. Converts to: SHA1, NSNumber. Test for being empty. Contains substrings and replace substrings from NSDictionary.
This file contains 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
#import <Foundation/Foundation.h> | |
@interface NSString (Extensions) | |
+ (NSString *)stringToSha1:(NSString *)str; | |
- (NSNumber*)stringToNSNumber; | |
- (BOOL)isEmpty; | |
- (BOOL)stringContainsSubString:(NSString *)subString; | |
- (NSString *)stringByReplacingStringsFromDictionary:(NSDictionary *)dict; | |
@end |
This file contains 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
#import "NSString+Extensions.h" | |
#import <CommonCrypto/CommonDigest.h> | |
@implementation NSString (Extensions) | |
+ (NSString*)stringToSha1:(NSString*)str { | |
const char *s = [str cStringUsingEncoding:NSUTF8StringEncoding]; | |
NSData *keyData = [NSData dataWithBytes:s length:strlen(s)]; | |
// This is the destination | |
uint8_t digest[CC_SHA1_DIGEST_LENGTH] = {0}; | |
// This one function does an unkeyed SHA1 hash of your hash data | |
CC_SHA1(keyData.bytes, keyData.length, digest); | |
// Now convert to NSData structure to make it usable again | |
NSData *out = [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH]; | |
NSString *hash = [out description]; | |
NSCharacterSet *doNotWants = [NSCharacterSet characterSetWithCharactersInString:@"<> "]; | |
hash = [[hash componentsSeparatedByCharactersInSet:doNotWants] componentsJoinedByString:@""]; | |
return hash; | |
} | |
- (NSNumber*)stringToNSNumber { | |
NSNumberFormatter* tmpFormatter = [[NSNumberFormatter alloc] init]; | |
[tmpFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; | |
NSNumber* theNumber = [tmpFormatter numberFromString:self]; | |
return theNumber; | |
} | |
- (BOOL)isEmpty { | |
if ([self length] <= 0 || self == (id)[NSNull null] || self == nil) { | |
return YES; | |
} | |
return NO; | |
} | |
- (BOOL)stringContainsSubString:(NSString *)subString { | |
NSRange aRange = [self rangeOfString:subString]; | |
if (aRange.location == NSNotFound) { | |
return NO; | |
} | |
return YES; | |
} | |
- (NSString*)stringByReplacingStringsFromDictionary:(NSDictionary*)dict { | |
NSMutableString* string = [self mutableCopy]; | |
for (NSString* target in dict) { | |
[string replaceOccurrencesOfString:target withString:[dict objectForKey:target] options:0 range:NSMakeRange(0, [string length])]; | |
} | |
return string; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment