How can I reverse a NSString?
Just use this convenient Objective-C method.
/** Reverse all characters of a string.
@param str String to invert.
@return Return the reversed string.
*/
+ (NSString *)reverseString:(NSString *)str {
NSMutableString *reversed = [NSMutableString string];
NSInteger charIndex = [str length];
while (charIndex > 0) {
charIndex--;
NSRange subRange = NSMakeRange(charIndex, 1);
[reversed appendString:[str substringWithRange:subRange]];
}
return reversed;
}
Download the ready-for-use source file (.m) of Reverse a NSString chars
A useful and helpful collection library of common Objective-C functions, methods, classes and categories.
Showing posts with label ios. Show all posts
Showing posts with label ios. Show all posts
October 3, 2013
October 1, 2013
Remap value in another range (eg: percentage or rate)
A simple math problem is remapping a value in another context, like a percentage.
So look to this useful Objective-C method.
/** Returns value remapped in a new range.
@param oldVal Original float value to be remapped.
@param oldMaxVal Maximum value of the original range.
@param oldMinVal Minimum value of the original range.
@param newMaxVal Maximum value of the new range.
@param newMinVal Minimum value of the new range.
@return Returns the float value remapped in the new range.
*/
+ (CGFloat)value:(CGFloat)oldVal inRemappedRangeDefinedByOldMax:(CGFloat)oldMaxVal oldMin:(CGFloat)oldMinVal
newMax:(CGFloat)newMaxVal newMin:(CGFloat)newMinVal {
CGFloat realRange = oldMaxVal - oldMinVal;
CGFloat newRange = newMaxVal - newMinVal;
CGFloat newVal = (((oldVal - oldMinVal) * newRange) / realRange) + newMinVal;
return newVal;
}
Download the ready-for-use source file (.m) of Remap value in another range (eg: percentage or rate)
So look to this useful Objective-C method.
/** Returns value remapped in a new range.
@param oldVal Original float value to be remapped.
@param oldMaxVal Maximum value of the original range.
@param oldMinVal Minimum value of the original range.
@param newMaxVal Maximum value of the new range.
@param newMinVal Minimum value of the new range.
@return Returns the float value remapped in the new range.
*/
+ (CGFloat)value:(CGFloat)oldVal inRemappedRangeDefinedByOldMax:(CGFloat)oldMaxVal oldMin:(CGFloat)oldMinVal
newMax:(CGFloat)newMaxVal newMin:(CGFloat)newMinVal {
CGFloat realRange = oldMaxVal - oldMinVal;
CGFloat newRange = newMaxVal - newMinVal;
CGFloat newVal = (((oldVal - oldMinVal) * newRange) / realRange) + newMinVal;
return newVal;
}
Download the ready-for-use source file (.m) of Remap value in another range (eg: percentage or rate)
September 28, 2013
Resize any UIView or even UIView subclasses
I made this Objective-C method because I was boring to write the same code for just an easy function like resizing an UIView.
/** Resize a UIView.
@param obj A UIView or a subclass of UIView.
@param size Target size.
@see moveView:toPoint:
*/
+ (void)resizeView:(UIView *)obj toSize:(CGSize)size {
if (!obj) { return; }
CGRect r = obj.frame;
r.size = size;
obj.frame = r;
}
Download the ready-for-use source file (.m) of Resize any UIView or even UIView subclasses
/** Resize a UIView.
@param obj A UIView or a subclass of UIView.
@param size Target size.
@see moveView:toPoint:
*/
+ (void)resizeView:(UIView *)obj toSize:(CGSize)size {
if (!obj) { return; }
CGRect r = obj.frame;
r.size = size;
obj.frame = r;
}
Download the ready-for-use source file (.m) of Resize any UIView or even UIView subclasses
September 27, 2013
Remove the extension from a file
A convenient and easy to remember function for removing the file extension.
/** Returns only the name of a file without its extension.
It's only a shortcut for `[[ NSString lastPathComponent] stringByDeletingPathExtension]`.
@param str Name of the file (or even the full path).
@return Returns the file name without extension.
*/
+ (NSString *)removeExtensionFromFile:(NSString *)str {
return [[str lastPathComponent] stringByDeletingPathExtension];
}
Download the ready-for-use source file (.m) of Remove the extension from a file
/** Returns only the name of a file without its extension.
It's only a shortcut for `[[ NSString lastPathComponent] stringByDeletingPathExtension]`.
@param str Name of the file (or even the full path).
@return Returns the file name without extension.
*/
+ (NSString *)removeExtensionFromFile:(NSString *)str {
return [[str lastPathComponent] stringByDeletingPathExtension];
}
Download the ready-for-use source file (.m) of Remove the extension from a file
September 26, 2013
Get current date and time in a well-kwnown format
How to get the current date and time printed out in standard formats?
Using NSDateFormatter is quite a joke, so this is a powerful function.
/** Get the current date and time in any of the standard formats.
Parameter "format" must be one of these values:
0: "dd/MM/yyyy - HH:mm"
1: "dd_MM_yyyy_HH_mm_ss"
2: "yyyy-MM-dd"
3: "HH:mm:ss"
4: "dd/MM/yyyy - HH:mm:ss"
@param format Type of format and therefore also the result type.
@return Returns a string representing the current date and time using selected format.
*/
+ (NSString *)currentDateAndTimeUsingFormatMode:(NSInteger)format {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
switch (format) {
case 0:
[formatter setDateFormat:@"dd/MM/yyyy - HH:mm"];
break;
case 1:
[formatter setDateFormat:@"dd_MM_yyyy_HH_mm_ss"];
break;
case 2:
[formatter setDateFormat:@"yyyy-MM-dd"];
break;
case 3:
[formatter setDateFormat:@"HH:mm:ss"];
break;
case 4:
[formatter setDateFormat:@"dd/MM/yyyy - HH:mm:ss"];
break;
default:
[formatter setDateFormat:@"dd/MM/yyyy - HH:mm"];
break;
}
return [formatter stringFromDate:[NSDate date]];
}
Download the ready-for-use source file (.m) of Get current date and time in a well-kwnown format
Using NSDateFormatter is quite a joke, so this is a powerful function.
/** Get the current date and time in any of the standard formats.
Parameter "format" must be one of these values:
0: "dd/MM/yyyy - HH:mm"
1: "dd_MM_yyyy_HH_mm_ss"
2: "yyyy-MM-dd"
3: "HH:mm:ss"
4: "dd/MM/yyyy - HH:mm:ss"
@param format Type of format and therefore also the result type.
@return Returns a string representing the current date and time using selected format.
*/
+ (NSString *)currentDateAndTimeUsingFormatMode:(NSInteger)format {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
switch (format) {
case 0:
[formatter setDateFormat:@"dd/MM/yyyy - HH:mm"];
break;
case 1:
[formatter setDateFormat:@"dd_MM_yyyy_HH_mm_ss"];
break;
case 2:
[formatter setDateFormat:@"yyyy-MM-dd"];
break;
case 3:
[formatter setDateFormat:@"HH:mm:ss"];
break;
case 4:
[formatter setDateFormat:@"dd/MM/yyyy - HH:mm:ss"];
break;
default:
[formatter setDateFormat:@"dd/MM/yyyy - HH:mm"];
break;
}
return [formatter stringFromDate:[NSDate date]];
}
Download the ready-for-use source file (.m) of Get current date and time in a well-kwnown format
September 25, 2013
Get the maximum available width (or height) for items in a box
I have a UIView container and some items with fixed size.
What's the maximum allowed space betweem them?
/** Returns the maximum space between items so that they could stay within a container.
@param numItems Number of items that must stay within a given container.
@param itemDimenions Size of single item.
@param containerDim Size of container.
@return Returns the dimension of the space between all items.
@see maxNumberOfItemsWithDimension:minSpacer:inContainerOfDimension:
*/
+ (CGFloat)maxSpaceBetweenItems:(NSInteger)numItems withDimension:(CGFloat)itemDimenions inContainerOfDimension:(CGFloat)containerDim {
return (containerDim - numItems * itemDimenions) / (numItems + 1);
}
Download the ready-for-use source file (.m) of Get the maximum available width (or height) for items in a box
What's the maximum allowed space betweem them?
/** Returns the maximum space between items so that they could stay within a container.
@param numItems Number of items that must stay within a given container.
@param itemDimenions Size of single item.
@param containerDim Size of container.
@return Returns the dimension of the space between all items.
@see maxNumberOfItemsWithDimension:minSpacer:inContainerOfDimension:
*/
+ (CGFloat)maxSpaceBetweenItems:(NSInteger)numItems withDimension:(CGFloat)itemDimenions inContainerOfDimension:(CGFloat)containerDim {
return (containerDim - numItems * itemDimenions) / (numItems + 1);
}
Download the ready-for-use source file (.m) of Get the maximum available width (or height) for items in a box
September 24, 2013
Get the maximum available items that could stay in a box
I have a UIView container and I need to put some items with fixed size in t.
How many objects can I have?
/** Returns the maximum number of items that could stay within a container.
It takes into account also a minimum spacer between items.
@param itemDimension Size of single item.
@param itemMinSpacer Minimum space between items.
@param containerDim Size of container.
@return Returns the number of maximum items that can fit into the container.
@see maxSpaceBetweenItems:withDimension:inContainerOfDimension:
*/
+ (NSInteger)maxNumberOfItemsWithDimension:(CGFloat)itemDimension minSpacer:(CGFloat)itemMinSpacer inContainerOfDimension:(CGFloat)containerDim {
CGFloat num = (containerDim - itemMinSpacer) / (itemMinSpacer + itemDimension);
return floorf(num);
}
Download the ready-for-use source file (.m) of Get the maximum available items that could stay in a box
How many objects can I have?
/** Returns the maximum number of items that could stay within a container.
It takes into account also a minimum spacer between items.
@param itemDimension Size of single item.
@param itemMinSpacer Minimum space between items.
@param containerDim Size of container.
@return Returns the number of maximum items that can fit into the container.
@see maxSpaceBetweenItems:withDimension:inContainerOfDimension:
*/
+ (NSInteger)maxNumberOfItemsWithDimension:(CGFloat)itemDimension minSpacer:(CGFloat)itemMinSpacer inContainerOfDimension:(CGFloat)containerDim {
CGFloat num = (containerDim - itemMinSpacer) / (itemMinSpacer + itemDimension);
return floorf(num);
}
Download the ready-for-use source file (.m) of Get the maximum available items that could stay in a box
September 22, 2013
Save raw data to a local file
How can I save NSData to a persistent local file in iOS SDK?
The answer is pretty simple: use this helpful Objective-C method.
You need:
- http://objective-c-functions.blogspot.com/2013/07/create-directory-in-ios-file-system.html
/** Saves data to device filesystem and returns its path.
@param data Data to save.
@param fileName String representing the name of the file in which data get stored.
@param localFolder Full path of folder that contains the file.
@return Returns file path of saved data.
*/
+ (NSString *)saveData:(NSData *)data toLocalFile:(NSString *)fileName inFolder:(NSString *)localFolder {
// If folder does not exist then it will be created on the fly.
BOOL isDir;
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:localFolder isDirectory:&isDir];
if (!exists || !isDir) {
[LMFunctions createFolderWithName:localFolder];
}
// Save the file.
NSString *filePath = [localFolder stringByAppendingPathComponent:fileName];
[data writeToFile:filePath atomically:YES];
return filePath;
}
Download the ready-for-use source file (.m) of Save raw data to a local file
The answer is pretty simple: use this helpful Objective-C method.
You need:
- http://objective-c-functions.blogspot.com/2013/07/create-directory-in-ios-file-system.html
/** Saves data to device filesystem and returns its path.
@param data Data to save.
@param fileName String representing the name of the file in which data get stored.
@param localFolder Full path of folder that contains the file.
@return Returns file path of saved data.
*/
+ (NSString *)saveData:(NSData *)data toLocalFile:(NSString *)fileName inFolder:(NSString *)localFolder {
// If folder does not exist then it will be created on the fly.
BOOL isDir;
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:localFolder isDirectory:&isDir];
if (!exists || !isDir) {
[LMFunctions createFolderWithName:localFolder];
}
// Save the file.
NSString *filePath = [localFolder stringByAppendingPathComponent:fileName];
[data writeToFile:filePath atomically:YES];
return filePath;
}
Download the ready-for-use source file (.m) of Save raw data to a local file
September 21, 2013
NSString to CGFloat conversion with custom decimal separator
Useful method for converting a NSString text to CGFloat value.
/** Returns a float from a string with arbitrary decimal separator.
@param str String representing a floating number.
@param separator String of decimal separator.
@return Returns the float value.
@see stringFromFloat:usingSeparatorForDecimal:
*/
+ (CGFloat)floatFromString:(NSString *)str withSeparatorForDecimal:(NSString *)separator {
return [[str stringByReplacingOccurrencesOfString:separator withString:@"."] floatValue];
}
Download the ready-for-use source file (.m) of NSString to CGFloat conversion with custom decimal separator
/** Returns a float from a string with arbitrary decimal separator.
@param str String representing a floating number.
@param separator String of decimal separator.
@return Returns the float value.
@see stringFromFloat:usingSeparatorForDecimal:
*/
+ (CGFloat)floatFromString:(NSString *)str withSeparatorForDecimal:(NSString *)separator {
return [[str stringByReplacingOccurrencesOfString:separator withString:@"."] floatValue];
}
Download the ready-for-use source file (.m) of NSString to CGFloat conversion with custom decimal separator
September 19, 2013
Write and Append text to file
Sometimes you need to write to an already existing file, that is append text to file.
Here's an example.
/** Append text to a file located in the /Documents directory.
If file does not exist it will be created from scratch.
@param str String to write.
@param fileName Name of the file.
*/
+ (void)writeAndAppendString:(NSString *)str toFile:(NSString *)fileName {
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if (0 < [paths count]) {
NSString *documentsDirPath = [paths objectAtIndex:0];
NSString *filePath = [documentsDirPath stringByAppendingPathComponent:fileName];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:filePath]) {
// Add the text at the end of the file.
NSFileHandle *fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
[fileHandler seekToEndOfFile];
[fileHandler writeData:data];
[fileHandler closeFile];
} else {
// Create the file and write text to it.
[data writeToFile:filePath atomically:YES];
}
}
}
Download the ready-for-use source file (.m) of Write and Append text to file
Here's an example.
/** Append text to a file located in the /Documents directory.
If file does not exist it will be created from scratch.
@param str String to write.
@param fileName Name of the file.
*/
+ (void)writeAndAppendString:(NSString *)str toFile:(NSString *)fileName {
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if (0 < [paths count]) {
NSString *documentsDirPath = [paths objectAtIndex:0];
NSString *filePath = [documentsDirPath stringByAppendingPathComponent:fileName];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:filePath]) {
// Add the text at the end of the file.
NSFileHandle *fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
[fileHandler seekToEndOfFile];
[fileHandler writeData:data];
[fileHandler closeFile];
} else {
// Create the file and write text to it.
[data writeToFile:filePath atomically:YES];
}
}
}
Download the ready-for-use source file (.m) of Write and Append text to file
September 17, 2013
Get the number of seconds in a time string
How many seconds there are in a given time string value?
/** Converts from string time to seconds.
Works only if used with this time format "HH:mm:ss".
@param str Time string in format "HH:mm:ss".
@return Returns the total number of seconds as NSNumber.
@see stringTimeFromSeconds:
*/
+ (NSNumber *)secondsInTimeString:(NSString *)str {
NSNumber *ret = [NSNumber numberWithLong:-1];
NSMutableArray *tempArr = [[NSMutableArray alloc] initWithArray:[str componentsSeparatedByString:@":"]];
if ([tempArr count] == 3) {
ret = [NSNumber numberWithLong: [[tempArr objectAtIndex:0] integerValue]*60*60 + [[tempArr objectAtIndex:1] integerValue]*60 + [[tempArr objectAtIndex:2] integerValue] ];
}
return ret;
}
Download the ready-for-use source file (.m) of Get the number of seconds in a time string
/** Converts from string time to seconds.
Works only if used with this time format "HH:mm:ss".
@param str Time string in format "HH:mm:ss".
@return Returns the total number of seconds as NSNumber.
@see stringTimeFromSeconds:
*/
+ (NSNumber *)secondsInTimeString:(NSString *)str {
NSNumber *ret = [NSNumber numberWithLong:-1];
NSMutableArray *tempArr = [[NSMutableArray alloc] initWithArray:[str componentsSeparatedByString:@":"]];
if ([tempArr count] == 3) {
ret = [NSNumber numberWithLong: [[tempArr objectAtIndex:0] integerValue]*60*60 + [[tempArr objectAtIndex:1] integerValue]*60 + [[tempArr objectAtIndex:2] integerValue] ];
}
return ret;
}
Download the ready-for-use source file (.m) of Get the number of seconds in a time string
September 16, 2013
Get time format from seconds
I have an amount of seconds that I would convert to a human readable string. What can I do?
Simply use my Objective-C method to accomplish it!
You need:
- http://objective-c-functions.blogspot.com/2013/08/add-zeros-to-digit-number.html
/** Converts from seconds to time string.
Returned time format is "HH:mm:ss".
@param sec Number of seconds as NSNumber.
@return Returns the string time as "HH:mm:ss".
@see secondsInTimeString:
*/
+ (NSString *)stringTimeFromSeconds:(NSNumber *)sec {
NSString *ret;
if ([sec longValue] < 0) {
LogError(@"Seconds are negative: %ld", sec.longValue);
ret = @"Undefined";
} else {
NSInteger h = floorf( [sec longValue] / 3600 );
NSInteger m = floorf( ([sec longValue]/60) % 60 );
NSInteger s = floorf( [sec longValue] % 60 );
ret = [NSString stringWithFormat:@"%@:%@:%@",
[LMFunctions twoDigits:h], [LMFunctions twoDigits:m], [LMFunctions twoDigits:s]];
}
return ret;
}
Download the ready-for-use source file (.m) of Get time format from seconds
Simply use my Objective-C method to accomplish it!
You need:
- http://objective-c-functions.blogspot.com/2013/08/add-zeros-to-digit-number.html
/** Converts from seconds to time string.
Returned time format is "HH:mm:ss".
@param sec Number of seconds as NSNumber.
@return Returns the string time as "HH:mm:ss".
@see secondsInTimeString:
*/
+ (NSString *)stringTimeFromSeconds:(NSNumber *)sec {
NSString *ret;
if ([sec longValue] < 0) {
LogError(@"Seconds are negative: %ld", sec.longValue);
ret = @"Undefined";
} else {
NSInteger h = floorf( [sec longValue] / 3600 );
NSInteger m = floorf( ([sec longValue]/60) % 60 );
NSInteger s = floorf( [sec longValue] % 60 );
ret = [NSString stringWithFormat:@"%@:%@:%@",
[LMFunctions twoDigits:h], [LMFunctions twoDigits:m], [LMFunctions twoDigits:s]];
}
return ret;
}
Download the ready-for-use source file (.m) of Get time format from seconds
September 14, 2013
Show or Hide all UIView subviews with a single function
While using Cocoa framework I often need to show or hide all child subviews of a parent UIView in a nutshell.
Use this Objective-C method in your Xcode projects!
/** Shows or hides all subviews of a View.
@param hide Boolean value that defines hide (true) or show (false).
@param ownerMainView A UIView or a subclass of UIView.
@see showAllSubviewsOf:
@see hideAllSubviewsOf:
@see removeAllSubviewsOfClass:fromView:
@see getAllSubviewsOfClass:fromView:
*/
+ (void)hide:(BOOL)hide allSubviewsOf:(UIView *)ownerMainView {
if (!ownerMainView) { return; }
for (NSInteger i=0; i<[ownerMainView.subviews count]; i++) {
[[ownerMainView.subviews objectAtIndex:i] setHidden:hide];
}
}
Download the ready-for-use source file (.m) of Show or Hide all UIView subviews with a single function
Use this Objective-C method in your Xcode projects!
/** Shows or hides all subviews of a View.
@param hide Boolean value that defines hide (true) or show (false).
@param ownerMainView A UIView or a subclass of UIView.
@see showAllSubviewsOf:
@see hideAllSubviewsOf:
@see removeAllSubviewsOfClass:fromView:
@see getAllSubviewsOfClass:fromView:
*/
+ (void)hide:(BOOL)hide allSubviewsOf:(UIView *)ownerMainView {
if (!ownerMainView) { return; }
for (NSInteger i=0; i<[ownerMainView.subviews count]; i++) {
[[ownerMainView.subviews objectAtIndex:i] setHidden:hide];
}
}
Download the ready-for-use source file (.m) of Show or Hide all UIView subviews with a single function
September 12, 2013
Check if a string is a valid time format
Ever wonder to check if a NSString might represent a valid time? I mean, hours : minutes : seconds ...
/** Check whether a string is a valid time in standard format "HH:mm:ss".
@param time String time to evaluate.
@return Returns true if it's a valid string time, false otherwise.
*/
+ (BOOL)isValidTimeString:(NSString *)time {
NSArray *temp = [time componentsSeparatedByString:@":"];
if ([temp count] != 3) { return NO; }
NSString *h = [temp objectAtIndex:0];
NSString *m = [temp objectAtIndex:1];
NSString *s = [temp objectAtIndex:2];
// Minutes and seconds must be of two digits. Hours, instead, might have any digits.
if (m.length != 2) { return NO; }
if (s.length != 2) { return NO; }
// Check values are numeric.
NSCharacterSet *num09 = [NSCharacterSet decimalDigitCharacterSet];
if (![num09 isSupersetOfSet:[NSCharacterSet characterSetWithCharactersInString:h]]) { return NO; }
if (![num09 isSupersetOfSet:[NSCharacterSet characterSetWithCharactersInString:m]]) { return NO; }
if (![num09 isSupersetOfSet:[NSCharacterSet characterSetWithCharactersInString:s]]) { return NO; }
// Minute and second values must be lesser than 60.
if ([m integerValue] >= 60) { return NO; }
if ([s integerValue] >= 60) { return NO; }
return YES;
}
Download the ready-for-use source file (.m) of Check if a string is a valid time format
/** Check whether a string is a valid time in standard format "HH:mm:ss".
@param time String time to evaluate.
@return Returns true if it's a valid string time, false otherwise.
*/
+ (BOOL)isValidTimeString:(NSString *)time {
NSArray *temp = [time componentsSeparatedByString:@":"];
if ([temp count] != 3) { return NO; }
NSString *h = [temp objectAtIndex:0];
NSString *m = [temp objectAtIndex:1];
NSString *s = [temp objectAtIndex:2];
// Minutes and seconds must be of two digits. Hours, instead, might have any digits.
if (m.length != 2) { return NO; }
if (s.length != 2) { return NO; }
// Check values are numeric.
NSCharacterSet *num09 = [NSCharacterSet decimalDigitCharacterSet];
if (![num09 isSupersetOfSet:[NSCharacterSet characterSetWithCharactersInString:h]]) { return NO; }
if (![num09 isSupersetOfSet:[NSCharacterSet characterSetWithCharactersInString:m]]) { return NO; }
if (![num09 isSupersetOfSet:[NSCharacterSet characterSetWithCharactersInString:s]]) { return NO; }
// Minute and second values must be lesser than 60.
if ([m integerValue] >= 60) { return NO; }
if ([s integerValue] >= 60) { return NO; }
return YES;
}
Download the ready-for-use source file (.m) of Check if a string is a valid time format
September 11, 2013
Check if a string is a valid MAC address
How to test if a string is a valid MAC address?
You need:
- http://objective-c-functions.blogspot.com/2013/08/check-if-number-is-valid-hex.html
/** Check if a MAC address is valid.
MAC address must be in the 12:34:56:78:9A:BC format.
@param mac String representing the MAC address to check.
@return Returns true if given MAC address is valid, false otherwise.
@see macAddressWithColonsFromString:
@see getMacAddressesFromFileAtPath:
*/
+ (BOOL)isValidMacAddress:(NSString *)mac {
// Must be 17 chars.
NSInteger len = [mac length];
if (len != 17) {
return NO;
}
// Let's valide all characters.
NSString *tempStr;
if (len == 17) {
// Loop by couples plus separator (eg: "C6:").
for (NSInteger i=0; i<=len; i+=3) {
// Position 0: hex char.
tempStr = [mac substringWithRange:NSMakeRange(i+0, 1)];
if (![LMFunctions isHexadecimalNumber:tempStr]) { return NO; }
// Position 1: hex char.
tempStr = [mac substringWithRange:NSMakeRange(i+1, 1)];
if (![LMFunctions isHexadecimalNumber:tempStr]) { return NO; }
// Position 2: separator.
if (i+2 < len) // Warning: last separator does not exist.
{
tempStr = [mac substringWithRange:NSMakeRange(i+2, 1)];
if (![tempStr isEqualToString:@":"]) { return NO; }
}
}
}
return YES;
}
Download the ready-for-use source file (.m) of Check if a string is a valid MAC address
You need:
- http://objective-c-functions.blogspot.com/2013/08/check-if-number-is-valid-hex.html
/** Check if a MAC address is valid.
MAC address must be in the 12:34:56:78:9A:BC format.
@param mac String representing the MAC address to check.
@return Returns true if given MAC address is valid, false otherwise.
@see macAddressWithColonsFromString:
@see getMacAddressesFromFileAtPath:
*/
+ (BOOL)isValidMacAddress:(NSString *)mac {
// Must be 17 chars.
NSInteger len = [mac length];
if (len != 17) {
return NO;
}
// Let's valide all characters.
NSString *tempStr;
if (len == 17) {
// Loop by couples plus separator (eg: "C6:").
for (NSInteger i=0; i<=len; i+=3) {
// Position 0: hex char.
tempStr = [mac substringWithRange:NSMakeRange(i+0, 1)];
if (![LMFunctions isHexadecimalNumber:tempStr]) { return NO; }
// Position 1: hex char.
tempStr = [mac substringWithRange:NSMakeRange(i+1, 1)];
if (![LMFunctions isHexadecimalNumber:tempStr]) { return NO; }
// Position 2: separator.
if (i+2 < len) // Warning: last separator does not exist.
{
tempStr = [mac substringWithRange:NSMakeRange(i+2, 1)];
if (![tempStr isEqualToString:@":"]) { return NO; }
}
}
}
return YES;
}
Download the ready-for-use source file (.m) of Check if a string is a valid MAC address
September 10, 2013
Check if a string is a valid IP address (IPv4 and IPv6)
This function checks if an IP address (either IPv4 or IPv6) is valid.
/** Check if an IP address is valid.
Looks for both IPv4 and IPv6.
Based on: http://stackoverflow.com/questions/1679152/how-to-validate-an-ip-address-with-regular-expression-in-objective-c/10971521#10971521
@param ip IP address as string.
@return Returns true if given IP address is valid, false otherwise.
*/
+ (BOOL)isValidIpAddress:(NSString *)ip {
const char *utf8 = [ip UTF8String];
// Check valid IPv4.
struct in_addr dst;
int success = inet_pton(AF_INET, utf8, &(dst.s_addr));
if (success != 1) {
// Check valid IPv6.
struct in6_addr dst6;
success = inet_pton(AF_INET6, utf8, &dst6);
}
return (success == 1);
}
Download the ready-for-use source file (.m) of Check if a string is a valid IP address (IPv4 and IPv6)
/** Check if an IP address is valid.
Looks for both IPv4 and IPv6.
Based on: http://stackoverflow.com/questions/1679152/how-to-validate-an-ip-address-with-regular-expression-in-objective-c/10971521#10971521
@param ip IP address as string.
@return Returns true if given IP address is valid, false otherwise.
*/
+ (BOOL)isValidIpAddress:(NSString *)ip {
const char *utf8 = [ip UTF8String];
// Check valid IPv4.
struct in_addr dst;
int success = inet_pton(AF_INET, utf8, &(dst.s_addr));
if (success != 1) {
// Check valid IPv6.
struct in6_addr dst6;
success = inet_pton(AF_INET6, utf8, &dst6);
}
return (success == 1);
}
Download the ready-for-use source file (.m) of Check if a string is a valid IP address (IPv4 and IPv6)
September 8, 2013
NSInteger to Word number conversion
Easy conversion between NSInteger and Word.
You need:
- http://objective-c-functions.blogspot.com/2013/08/int-to-hex-number-conversion.html
- http://objective-c-functions.blogspot.com/2013/08/hex-to-int-number-conversion.html
/** Convert an int to a Word defined by a low byte and a high byte.
@param intVal Integer value.
@return Returns an array in which first item is the low byte and second item is the high byte.
@see intFromWordWithLowByte:highByte:
*/
+ (NSArray *)highLowBytesFromInteger:(NSInteger)intVal {
NSString *hexVal = [[LMFunctions hexFromInt:intVal] substringFromIndex:2]; // Remove "0x".
NSMutableString *prefix = [[NSMutableString alloc] initWithString:@""];
NSInteger length = hexVal.length;
if (length < 4) {
for (NSInteger i=0; i<4-length; i++) {
[prefix appendString:@"0"];
}
}
hexVal = [NSString stringWithFormat:@"%@%@", prefix, hexVal];
NSString *hexValHigh = [hexVal substringToIndex:2];
NSString *hexValLow = [hexVal substringFromIndex:(hexVal.length - 2)];
Byte bH = [LMFunctions intFromHex:hexValHigh];
Byte bL = [LMFunctions intFromHex:hexValLow];
return [NSArray arrayWithObjects:[NSNumber numberWithInteger:bH], [NSNumber numberWithInteger:bL], nil];
}
Download the ready-for-use source file (.m) of NSInteger to Word number conversion
You need:
- http://objective-c-functions.blogspot.com/2013/08/int-to-hex-number-conversion.html
- http://objective-c-functions.blogspot.com/2013/08/hex-to-int-number-conversion.html
/** Convert an int to a Word defined by a low byte and a high byte.
@param intVal Integer value.
@return Returns an array in which first item is the low byte and second item is the high byte.
@see intFromWordWithLowByte:highByte:
*/
+ (NSArray *)highLowBytesFromInteger:(NSInteger)intVal {
NSString *hexVal = [[LMFunctions hexFromInt:intVal] substringFromIndex:2]; // Remove "0x".
NSMutableString *prefix = [[NSMutableString alloc] initWithString:@""];
NSInteger length = hexVal.length;
if (length < 4) {
for (NSInteger i=0; i<4-length; i++) {
[prefix appendString:@"0"];
}
}
hexVal = [NSString stringWithFormat:@"%@%@", prefix, hexVal];
NSString *hexValHigh = [hexVal substringToIndex:2];
NSString *hexValLow = [hexVal substringFromIndex:(hexVal.length - 2)];
Byte bH = [LMFunctions intFromHex:hexValHigh];
Byte bL = [LMFunctions intFromHex:hexValLow];
return [NSArray arrayWithObjects:[NSNumber numberWithInteger:bH], [NSNumber numberWithInteger:bL], nil];
}
Download the ready-for-use source file (.m) of NSInteger to Word number conversion
September 7, 2013
Word to NSInteger number conversion
Intermediate function that converts a Word into a NSInteger.
You need:
- http://objective-c-functions.blogspot.com/2013/08/hex-to-int-number-conversion.html
/** Convert a Word to an int.
@param lowByte The low byte of the word.
@param highByte The high byte of the word.
@return Returns the integer value of the word.
@see highLowBytesFromInteger:
*/
+ (NSInteger)intFromWordWithLowByte:(Byte)lowByte highByte:(Byte)highByte {
NSString *startHexAddressHigh = [NSString stringWithFormat:@"0x%X", highByte];
NSString *startHexAddressLow = [NSString stringWithFormat:@"0x%X", lowByte];
NSInteger res = [LMFunctions intFromHex:startHexAddressHigh] * 16 * 16;
res += [LMFunctions intFromHex:startHexAddressLow];
return res;
}
Download the ready-for-use source file (.m) of Word to NSInteger number conversion
You need:
- http://objective-c-functions.blogspot.com/2013/08/hex-to-int-number-conversion.html
/** Convert a Word to an int.
@param lowByte The low byte of the word.
@param highByte The high byte of the word.
@return Returns the integer value of the word.
@see highLowBytesFromInteger:
*/
+ (NSInteger)intFromWordWithLowByte:(Byte)lowByte highByte:(Byte)highByte {
NSString *startHexAddressHigh = [NSString stringWithFormat:@"0x%X", highByte];
NSString *startHexAddressLow = [NSString stringWithFormat:@"0x%X", lowByte];
NSInteger res = [LMFunctions intFromHex:startHexAddressHigh] * 16 * 16;
res += [LMFunctions intFromHex:startHexAddressLow];
return res;
}
Download the ready-for-use source file (.m) of Word to NSInteger number conversion
September 6, 2013
Get a list of items from a file (eg: MAC address)
I often save a set of items in a txt file so then I can "load" them directly from that file.
For example, this is a function which purpose is read MAC addresses from a given file. Of course you can adapt it to your needs.
/** Returns all the MAC addresses written in a file.
This function treats every line as a MAC address.
@param filePath The path of the file to search through.
@return An array containing all the MAC addresses found in the file.
@see macAddressWithColonsFromString:
@see isValidMacAddress:
*/
+ (NSArray *)getMacAddressesFromFileAtPath:(NSString *)filePath {
if (filePath) {
NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
NSArray *arr = [[NSArray alloc] initWithArray:[str componentsSeparatedByString:@"\n"]];
return arr;
} else {
return nil;
}
}
Download the ready-for-use source file (.m) of Get a list of items from a file (eg: MAC address)
For example, this is a function which purpose is read MAC addresses from a given file. Of course you can adapt it to your needs.
/** Returns all the MAC addresses written in a file.
This function treats every line as a MAC address.
@param filePath The path of the file to search through.
@return An array containing all the MAC addresses found in the file.
@see macAddressWithColonsFromString:
@see isValidMacAddress:
*/
+ (NSArray *)getMacAddressesFromFileAtPath:(NSString *)filePath {
if (filePath) {
NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
NSArray *arr = [[NSArray alloc] initWithArray:[str componentsSeparatedByString:@"\n"]];
return arr;
} else {
return nil;
}
}
Download the ready-for-use source file (.m) of Get a list of items from a file (eg: MAC address)
September 5, 2013
Host name to IP address
What's the IP address of that host? Use this convenient C method to check it out.
Although it's written in C, it works also in Objective-C and so in all your iOS and Mac OS projects.
/** Converts a host name to IP address.
Actual return data will be stored in the two parameters "addrp" and "familyp".
@param name The host name to convert.
@param addrp A pointer to a in_addr struct. This parameter will be overwritten with actual IP address.
@param familyp Address family (must be AF_INET). This parameter could be overwitten with actual address family type.
*/
void host2addr(char *name, struct in_addr *addrp, short *familyp) {
struct hostent *hp;
if ((hp=gethostbyname(name))) {
bcopy(hp->h_addr,(char *)addrp,hp->h_length);
if (familyp) *familyp = hp->h_addrtype;
} else if ((addrp->s_addr=inet_addr(name)) != -1) {
if (familyp) *familyp = AF_INET;
} else {
fprintf(stderr, "Unknown host : %s\n",name);
exit(1);
}
}
Download the ready-for-use source file (.m) of Host name to IP address
Although it's written in C, it works also in Objective-C and so in all your iOS and Mac OS projects.
/** Converts a host name to IP address.
Actual return data will be stored in the two parameters "addrp" and "familyp".
@param name The host name to convert.
@param addrp A pointer to a in_addr struct. This parameter will be overwritten with actual IP address.
@param familyp Address family (must be AF_INET). This parameter could be overwitten with actual address family type.
*/
void host2addr(char *name, struct in_addr *addrp, short *familyp) {
struct hostent *hp;
if ((hp=gethostbyname(name))) {
bcopy(hp->h_addr,(char *)addrp,hp->h_length);
if (familyp) *familyp = hp->h_addrtype;
} else if ((addrp->s_addr=inet_addr(name)) != -1) {
if (familyp) *familyp = AF_INET;
} else {
fprintf(stderr, "Unknown host : %s\n",name);
exit(1);
}
}
Download the ready-for-use source file (.m) of Host name to IP address
Subscribe to:
Posts (Atom)