{"id":24503,"date":"2015-11-24T11:34:37","date_gmt":"2015-11-24T06:04:37","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=24503"},"modified":"2015-11-24T11:34:37","modified_gmt":"2015-11-24T06:04:37","slug":"objective-c-utility-class-using-c-functions-in-ios","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/objective-c-utility-class-using-c-functions-in-ios\/","title":{"rendered":"Objective-C utility class using C functions in iOS"},"content":{"rendered":"<h2>Introduction<\/h2>\n<p>Like C, I would like to use C functions in \u00a0Objective-C class so i could\u00a0use C functions anywhere anytime without using class name.<\/p>\n<p><strong>Defining function:<\/strong> Function definition in C programming language is as follows \u2212<\/p>\n<div>\n<table>\n<tbody>\n<tr>\n<td>\n<pre>return_type function_name(parameter list)\r\n{\r\n    body of the function\r\n}<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p>In Objective-C, you can create a Objective-C class having NSObject superclass.<\/p>\n<p>I am creating a <strong>CommonFunctions.h<\/strong> &amp; <strong>CommonFunctions.m<\/strong>\u00a0as given below:<\/p>\n<h2>Header File (CommonFunctions.h)<\/h2>\n<table>\n<tbody>\n<tr>\n<td>\n<pre>#import &lt;UIKit\/UIKit.h&gt;\r\n\r\n#pragma mark - NSUserDefaults\r\n\r\nvoid saveDataWithKey(id data,NSString *key);\r\nid dataWithKey(NSString *key);\r\n\r\n#pragma mark - Notification\r\n\r\nvoid removeNotification(id sender);\r\nvoid postNotification(NSString *name, id object);\r\nvoid addNotification(NSString *name, id sender,SEL selector,id object);\r\n\r\n#pragma mark - NSFileManager\r\n\r\nBOOL isFileExist(NSString* path);\r\nvoid removePath(NSString* path);\r\nvoid createDirectory(NSString* path);\r\nBOOL isDirectoryExist(NSString* path);\r\n\r\n#pragma mark - String\r\n\r\n\/\/ function to check empty or null string\r\nBOOL nonEmptyString(NSString *string);\r\n\r\n#pragma mark - Custom\r\n\r\nvoid customBackButtonForController(id controller);\r\nvoid startShake (UIView* view);\r\nvoid shakeEnded (NSString * animationID, BOOL finished, void *context);\r\nvoid showAlert (NSString * title,NSString * message);\r\n\/\/Function to calculate height for label according to text at runtime\r\nCGSize dynamicHeightForLabel(NSString *text,float width, UIFont *font);\r\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<h2>Implementation File (CommonFunctions.m)<\/h2>\n<table>\n<tbody>\n<tr>\n<td>\n<pre>#import \"CommonFunctions.h\"\r\n\r\n#pragma mark - NSUserDefaults\r\n\r\nvoid saveDataWithKey(id data,NSString *key){\r\n\r\n    NSData *data_ = [NSKeyedArchiver archivedDataWithRootObject:data];\r\n    [[NSUserDefaults standardUserDefaults] setObject:data_ forKey:key];\r\n    [[NSUserDefaults standardUserDefaults] synchronize];\r\n}\r\n\r\nid dataWithKey(NSString *key){\r\n\r\n    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:key];\r\n    if(!data)\r\n        return nil;\r\n    return [NSKeyedUnarchiver unarchiveObjectWithData:data];\r\n}\r\n\r\n#pragma mark - Notification\r\n\r\nvoid removeNotification(id sender){\r\n    [[NSNotificationCenter defaultCenter] removeObserver:sender];\r\n}\r\nvoid postNotification(NSString *name, id object){\r\n    [[NSNotificationCenter defaultCenter] postNotificationName:name object:object];\r\n}\r\nvoid addNotification(NSString *name, id sender,SEL selector,id object){\r\n    [[NSNotificationCenter defaultCenter] addObserver:sender \r\n                                             selector:selector \r\n                                                 name:name \r\n                                               object:object];\r\n}\r\n\r\n#pragma mark - NSFileManager\r\n\r\nBOOL isFileExist(NSString* path){\r\n\r\n    return  [[NSFileManager defaultManager] fileExistsAtPath:path];\r\n}\r\n\r\nvoid removePath(NSString* path){\r\n\r\n    [[NSFileManager defaultManager] removeItemAtPath:path error:nil];\r\n}\r\n\r\nvoid createDirectory(NSString* path){\r\n\r\n    [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];\r\n}\r\n\r\nBOOL isDirectoryExist(NSString* path){\r\n\r\n    BOOL is = NO;\r\n    if([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&amp;is])\r\n        return YES;\r\n    return NO;\r\n}\r\n\r\n#pragma mark- String\r\n\r\nBOOL nonEmptyString(NSString *string){\r\n  if (string == (id)[NSNull null] || string.length == 0){\r\n        return NO;\r\n    }else{\r\n        NSMutableString *inputString = [NSMutableString stringWithString:string];\r\n        [inputString replaceOccurrencesOfString:@\" \" \r\n                                     withString:@\"\" \r\n                                        options:NSCaseInsensitiveSearch \r\n                                          range:NSMakeRange(0, [string length])];\r\n        \r\n        if(inputString.length == 0)\r\n            return NO;\r\n        return YES;\r\n    }\r\n\r\n}    \r\n\r\n#pragma mark- Custom\r\n\r\nvoid startShake (UIView* view){\r\n\r\n    CGAffineTransform leftShake = CGAffineTransformMakeTranslation(-5, 0);\r\n    CGAffineTransform rightShake = CGAffineTransformMakeTranslation(0, 0);\r\n    \r\n    view.transform = leftShake;  \/\/ starting point\r\n    \r\n    [UIView beginAnimations:@\"shake_button\" context:(__bridge void *)(view)];\r\n    [UIView setAnimationRepeatAutoreverses:YES]; \/\/ important\r\n    [UIView setAnimationRepeatCount:3];\r\n    [UIView setAnimationDuration:0.06];\r\n    \r\n    shakeEnded(@\"shake_button\", YES, (__bridge void *)(view));\r\n    view.transform = rightShake; \/\/ end here &amp; auto-reverse\r\n    [UIView commitAnimations];\r\n}\r\n\r\nvoid shakeEnded (NSString * animationID, BOOL finished, void *context){\r\n\r\n    if (finished) {\r\n        UIView* item = (__bridge UIView *)context;\r\n        item.transform = CGAffineTransformIdentity;\r\n    }\r\n}\r\n\r\nvoid showAlert (NSString * title,NSString * message){\r\n\r\n    UIAlertView *alerView = [[UIAlertView alloc]initWithTitle:title \r\n                                                      message:message \r\n                                                     delegate:nil \r\n                                            cancelButtonTitle:nil \r\n                                            otherButtonTitles:@\"Ok\", nil];\r\n    [alerView show];\r\n}\r\n\r\nvoid customBackButtonForController (UIViewController *controller){\r\n    \r\n    UIButton *customBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];\r\n    customBackBtn.frame = CGRectMake(0, 0, 22, 22);\r\n    BUTTONIMAGE(customBackBtn, \"backArrow\");\r\n    BUTTON_ADD_TARGET(customBackBtn,controller,backBtnAciton:);\r\n    UIBarButtonItem *leftBarBtnItem = [[UIBarButtonItem alloc] initWithCustomView:customBackBtn];\r\n    [controller.navigationItem setLeftBarButtonItem:leftBarBtnItem animated:YES];\r\n}\r\n\r\nCGSize dynamicHeightForLabel(NSString *text,float width, UIFont *font){\r\n   \r\n    CGSize constrainedSize = CGSizeMake(width, CGFLOAT_MAX);\r\n    NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:font,\r\n    NSFontAttributeName,nil];\r\n    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:text\r\n    attributes:attributesDictionary];\r\n    CGRect requiredHeight = [string boundingRectWithSize:constrainedSize\r\n    options:NSStringDrawingUsesLineFragmentOrigin context:nil];\r\n    \r\n    if (requiredHeight.size.width &gt; width) {\r\n        requiredHeight = CGRectMake(0, 0, width, requiredHeight.size.height);\r\n    }\r\n    return requiredHeight.size;\r\n}\r\n\r\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2>How to call CommonFunctions.h methods<\/h2>\n<p>Simple like other Objective-C class import &#8220;CommonFunctions.h&#8221; class in required controller or views and access methods by calling method name directly.<\/p>\n<p>Example:<\/p>\n<table>\n<tbody>\n<tr>\n<td>\n<pre>#import \"CommonFunctions.h\"\r\n\r\nNSString *string = @\"string\";\r\n\r\nif(notEmptyString(string)){\r\n  NSLog(@\"string is not empty\");\r\n}else{\r\n  NSLog(@\"string is empty or null\");\r\n}\r\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>&nbsp;<\/p>\n<h2>Download<\/h2>\n<p>You can download the CommonFunctions.h &amp; CommonFunctions.m from\u00a0<a href=\"\/blog\/wp-ttn-blog\/uploads\/2015\/11\/CommonFunctions.zip\">here<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction Like C, I would like to use C functions in \u00a0Objective-C class so i could\u00a0use C functions anywhere anytime without using class name. Defining function: Function definition in C programming language is as follows \u2212 return_type function_name(parameter list) { body of the function } In Objective-C, you can create a Objective-C class having NSObject [&hellip;]<\/p>\n","protected":false},"author":169,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":26},"categories":[1400,1],"tags":[4848,2782,2783],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/24503"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/169"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=24503"}],"version-history":[{"count":0,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/24503\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=24503"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=24503"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=24503"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}