Moving or relocating a git repository to a new server

August 12th, 2014

If you or your company decides to move git repository to a new server location, here is quick commands that you would need to move or relocate your source code repository.

// create a new origin named new-origin and point it to new server
git remote add new-origin  // ex:
// push all code and tags to new origin
git push --all new-origin
git push --tags new-origin
// remove old origin and rename new origin to make it default. This will enable all new commits to go to new server
git remote rm origin
git remote rename new-origin origin

If these commands helped you, don’t forgot to leave a comment.

Source: Smashing Magazine

How to split NSString at uppercase letters

October 31st, 2013

In course of developing one of the applications, I came across a requirement where I had to convert controller names into readable user understandable names. Though I have named controllers by their relevancy, still I wanted to make it look good to a general user as well. And fortunately, StackOverflow came to my rescue.

I got this piece of code which perfectly added space to the names of controller classes and then removed ‘Controller’ word from it thus making it perfectly readable and easily understandable.

NSString *string = NSStringFromClass([self class]);
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:@"([a-z])([A-Z])" options:0 error:NULL];
NSString *newString = [[regexp stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, string.length) withTemplate:@"$1 $2"] stringByReplacingOccurrencesOfString:@" Controller" withString:@""] ];

Hope some of my readers will find it helpful. Do leave a comment, if you found it helpful.


Two ways to load custom UITableViewCell from nib

July 17th, 2012

Create a custom class subclassing UITableViewCell. Make sure to check the nib check box.
Add desired controls on the nib and link them with outlets.

Method 1:

  • Set identifier of table view cell object in Interface Builder to the identifier, that is to be used in code to make object of cells.
  • Write following code in cellForRowAtIndexPath method:
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
 if (cell == nil)
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@”iCodeBlogCustomCell” owner:nil options:nil];
 for(id currentObject in topLevelObjects)
if([currentObject isKindOfClass:[CustomCell class]])
cell = (CustomCell *)currentObject;

Method 2:

  • Create a custom init method in custom cell view class with following code:
- (id)init
self = [[[[NSBundle mainBundle] loadNibNamed:@"NibName" owner:self options:nil] objectAtIndex:0] retain];
if (self)
// any further initialization
return self;
  • Write following code in cellForRowAtIndexPath method:
static NSString *CellIdentifier = @"CustomCell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
cell = [[[CustomCell alloc] init] autorelease];
 // setup your cell
 return cell;

Do let me know if none of the above works for you.

How to get Device Model in Objective-C

June 14th, 2012

In one of my recent apps, I was required to track usage of application based on device model (i.e. iPhone 3, iPhone 3GS, iPad 1 etc.). But the problem was that there is was not any direct API available to provide this information. After some research I found this solution:

Import utsname class in your project:

#import <sys/utsname.h>

Create method to identify Device’s Model Number:

- (NSString *)deviceModel
    struct utsname systemInfo;
    return [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];

Create a method to convert Device’s model number into Platform String:

- (NSString *) platformString
    NSString *platform = [self deviceModel];
    if ([platform isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    if ([platform isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone3,3"])    return @"Verizon iPhone 4";
    if ([platform isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([platform isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([platform isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([platform isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([platform isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    if ([platform isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([platform isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([platform isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
    if ([platform isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([platform isEqualToString:@"i386"])         return @"Simulator";
    if ([platform isEqualToString:@"x86_64"])       return @"Simulator";
    return platform;

Call platformString method to get device’s model name:

NSString *deviceName = [self platformString];

This quick and short piece of code saved my life in getting my task done, which was to track the usage of application based on device mode. I hope you will be benefitted by this piece of code as well. If you have any comment or suggestion related to this article, please drop me a comment.

Thanks and enjoy coding.

How to use iPhone contacts in your own application

February 13th, 2011

In this how to series, I have come up with yet another code snippet, which allows you to use iPhone’s contact data into your own application. The code is:

ABAddressBookRef myAddressBook = ABAddressBookCreate();
NSArray *allPeople = (NSArray *)ABAddressBookCopyArrayOfAllPeople(myAddressBook);
contactList = [[NSMutableArray alloc]initWithCapacity:[allPeople count]];
for (id record in allPeople) {
CFTypeRef phoneProperty = ABRecordCopyValue((ABRecordRef)record, kABPersonPhoneProperty);
NSArray *phones = (NSArray *)ABMultiValueCopyArrayOfAllValues(phoneProperty);
//NSLog(@”phones array: %@”, phones);
NSString* contactName = (NSString *)ABRecordCopyCompositeName((ABRecordRef)record);
NSMutableDictionary *newRecord = [[NSMutableDictionary alloc] init];
[newRecord setObject:contactName forKey:@"name"];
//[contactName release];
NSMutableString *newPhone = [[NSMutableString alloc] init];
for (NSString *phone in phones) {
//NSString *fieldData = [NSString stringWithFormat:@"%@: %@", contactName, phone];
if(![newPhone isEqualToString:@""])
[newPhone appendString:@", "];
[newPhone appendString:phone];
[newRecord setObject:newPhone forKey:@"phone"];
[newPhone release];
[phones release];
[contactList addObject:newRecord];
//[newPhone release];
// NSLog(@”Final data: %@”, contactList);

How to save current screen to iPhone library

January 23rd, 2011

Here is a quick post, in which I am posting a quick snippet to capture the current screen of iPhone and save it to the phone library. This piece of code will be helpful in generating screen-shot of any iPhone application programmatically.

  1. -(void)saveScreen
  2. {
  3. CGRect myRect = [self.view bounds];
  4. UIGraphicsBeginImageContext(myRect.size);
  5. CGContextRef ctx = UIGraphicsGetCurrentContext();
  6. [[UIColor blackColor] set];
  7. CGContextFillRect(ctx, myRect);
  8. [self.view.layer renderInContext:ctx];
  9. UIImage *image1 = UIGraphicsGetImageFromCurrentImageContext();
  10. UIImageWriteToSavedPhotosAlbum(image1, nil, nil, nil);
  11. UIGraphicsEndImageContext();
  12. }

Please leave your comments here so that I can find out, if you find this snippet useful or not

Using NSUserDefaults in iPhone app – Interesting fact.

November 1st, 2010

In one of my projects, I was using User Defaults for the first time. Then I came across a very interesting problem. I was writing this code for setting value to user defaults:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:@"Value" forKey:@"key"];

After setting the values this way, I tried retrieving the value for the key in next session, it simply did not return correct value.

After googling for a while, I came to know about this line and it worked perfectly:

[prefs synchronize];

Thus, I came to know that in order to use User Defaults, one have to use this synchronize function. The final code looks like:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:@"Value" forKey:@"key"];
[prefs synchronize];


Merging two images in objective-c

October 28th, 2010

While researching about image manipulation for my next project, I came across an interesting piece of code, using which, we can merge two images into a single image. Here’s the code:

-(UIImage*)mergeImage:(UIImage*)mask overImage:(UIImage*)source inSize:(CGSize)size
//Capture image context ref
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();

//Draw images onto the context
[source drawInRect:CGRectMake(0, 0, source.size.width, source.size.height)];
[mask drawInRect:CGRectMake(0, 0, mask.size.width, mask.size.height)];

return viewImage;


Got the reference from here.


Date formatting in Cocoa

September 5th, 2010

Date formatters format the textual representation of cells that contain date objects (including Gregorian dates), and convert textual representations of dates and times into date objects.” – Apple Documentation.

While creating an app, you generally come across a situation, when you require custom date format to represent dates in user friendly manner. For this purpose, Cocoa provides date formatter class. Using a date formatter, we can express dates colloquially, such as “today,” “day after tomorrow,” and “a month from today.”

Here’s the example of date formatter:
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc]initWithDateFormat:@”%1m/%1d/%Y” allowNaturalLanguage:NO] autorelease];

NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:118800];

NSString *formattedDateString = [dateFormatter stringFromDate:date];

NSLog(@”formattedDateString: %@”, formattedDateString);

// Output: formattedDateString: 1/2/2001

Below is the list of possible date conversions using date formatter (More detail on date conversion and range of conversions can be found here):




A '%' character


Abbreviated weekday name


Full weekday name


Abbreviated month name


Full month name


Shorthand for “%X %x“, the locale format for date and time


Day of the month as a decimal number (01-31)


Same as %d but does not print the leading 0 for days 1 through 9 (unlike strftime(), does not print a leading space)


Milliseconds as a decimal number (000-999)


Hour based on a 24-hour clock as a decimal number (00-23)


Hour based on a 12-hour clock as a decimal number (01-12)


Day of the year as a decimal number (001-366)


Month as a decimal number (01-12)


Minute as a decimal number (00-59)


AM/PM designation for the locale


Second as a decimal number (00-59)


Weekday as a decimal number (0-6), where Sunday is 0


Date using the date representation for the locale, including the time zone (produces different results from strftime())


Time using the time representation for the locale (produces different results from strftime())


Year without century (00-99)


Year with century (such as 1990)


Time zone name (such as Pacific Daylight Time; produces different results from strftime())


Time zone offset in hours and minutes from GMT (HHMM)

Hope this helps you in programming. Do let me know your views on it.

Enjoy Coding!

How to show UIWebView without background

August 29th, 2010

I was working on an iPhone app, when I came across a problem, where I had to use UIWebView to show some of the data, but the background should not be shown (I had a background image for my app, and the content of web view should have to be shown just over the app background). But the background of web-view was showing as white color. After googling for sometime, I came across this small piece of code, which solved my problem:

[myWebView setBackgroundColor:[UIColor clearColor]];
[myWebView setOpaque:NO];
[myWebView loadHTMLString:@”<html>\
<body style=”‘background-color:transparent;’”>\

And this small piece worked for me.