Archive for the 'Objective-C' Category

NSDate without time portion

The Problem

Sometimes you need to make comparation with dates, but NSDate is not actually a Date like YYYYMMDD. In fact NSDate conceptually store time relative to Jan 1, 2001, GMT. So if you get a [NSDate date] and two seconds after you get another [NSDate date] you will have two different dates.

The Solution, well… One solution of many

One way to solve this problem is to set the time portion of NSDate to a arbitrary value like 00:00:00. To do this take a look in the code that follows:

+(NSDate *) normalizedDate {
 NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
 // [gregorian setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
 [gregorian setTimeZone:[NSTimeZone localTimeZone]];

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | kCFCalendarUnitWeekday | kCFCalendarUnitWeekdayOrdinal fromDate:[NSDate date]];

NSDateComponents *normalized = NSDateComponents.alloc.init;
 [normalized setWeekday: [components weekday]];
 [normalized setWeekdayOrdinal:[components weekdayOrdinal]];
 [normalized setMonth:[components month]];
 [normalized setYear:[components year]];

return [gregorian dateFromComponents:normalized];

In some situations you will want to set a specific time zone, to do so I suggest you to put time zone at “GMT” as the comented part of the code above.

Basic ShareKit customization

ShareKit is an open source framework for iOS apps to add capabilities to share information with many internet services.

Your app can share information with this supported services: Delicious, Email, Facebook, Google Reader, Instapaper, Pinboard, Read It Later, Tumblr, Twitter.

ShareKit has your own interface to connect with the services, but you can customize Sharekit to connect those services in your own way. Let get start our step-by-step tutorial.

1) Create your project.

a. Enter in xcode and create a new project with “view-based application” template;
b. Name the project as “SharekitTest”;
c. Place a UIButton in the SharekiTestViewController.xib;

d. Control-drag the UIButton to the location in the SharekiTestViewController.h you want. When you release the mouse button, Xcode displays a small dialog. Set the connection field to “Action” and the name field to “facebookButtonTapped”

e. Save your project.

2) Add Sharekit to your app

a. Take a look at
b. Follow steps 1 and 2 and get back to this tutorial

3) Register your app to developer’s service site.

a. Register your app to, login with your account;
b. Fill the form with your app’s information;
c. You should have consumer key and consumer secret now.

4) Locate and open the file SHKConfig.h an fill the key and secret.
// Facebook -
// If SHKFacebookUseSessionProxy is enabled then SHKFacebookSecret is ignored and should be left blank

#define SHKFacebookUseSessionProxy  NO
#define SHKFacebookKey				@"248989898989898849"
#define SHKFacebookSecret			@"7a6242232323232323236b4997138b1c"
#define SHKFacebookSessionProxyURL  @""
5) Import the headers in the SharekiTestViewController.h
#import "SHK.h"
#import "SHKFacebook.h"
6) Insert the code below in the “FacebookButtonTapped” method in SharekiTestViewController.m to share what you want.
- (IBAction)FacebookButtonTapped:(id)sender {
    SHKItem *item;
    NSURL *url = [NSURL URLWithString:@""""];
    item = [SHKItem URL:url title:@"Checkout this site"];
    [SHKFacebook shareItem:item];

In this code we create an SHKItem. It has four methods, one for each information you want to share: URL, Images, Text and Files. Then we create an url, set the url to the SHKItem and finally set the item to shareItem method to be published.

It’s done ! You can do a lot more customizations, go to the sharekit website and have fun!

Add and delete customized UITableViewCell

Apple AppStore is a huge success. There is more than 400 thousands apps’s. So if you want to be noted is better you create a very interesting app. To do that in most cases you will want to customize the UI of your app. One very powerfull customization is change the tableview. You can do a lot of stuff changing the tableviewcell and probably you will want to put another UI elements inside the cell. In that case we may have a tricky situation when you have to add and remove customized cells from one tableview.

Animate the deletion from tableView

Apple provide an animated way to remove cells from tableView. You only have to remove the item you want from the collection that store tableview’s data (a NSMutableArray, for example) and then call deleteRowsAtIndexPaths method from tableview as follows:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
    if ([self.tableViewData count]>1) {
        // If row is deleted, remove it from the list.
        if (editingStyle == UITableViewCellEditingStyleDelete)
            [self.tableView beginUpdates];
            [self.tableViewData removeObjectAtIndex:indexPath.row];

            // Animate the deletion from the table.
            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
            [self.tableView endUpdates];

Modifying layer that is being finalized

Imagine you have tableviews with cells that has textfields. And imagine you want to add and remove cells from this tableview. In that case you may have a problem with the cell deletion procedure. If you add and delete cells a few times probably you will receive this error message from the compiler:

GNU gdb 6.3.50-20050815 (Apple version gdb-1518) (Sat Feb 12 02:52:12 UTC 2011)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin".sharedlibrary apply-load-rules all
Attaching to process 663.
2011-07-10 20:35:27.117 iScoreKeeper[663:207] modifying layer that is being finalized - 0x4e40450
Current language:  auto; currently objective-c

Why is it occur?

The tableView cell’s content are referred in two collections – into the collection that store tableview’s data and in the tableview itself. So, when you delete one cell the animated deletion procedure is executed in two steps: first it removes the object from the tableview model and second removes the cell from tableview.

In the case of our example, we have a NSMutableArray with textfields as cell’s content. When you remove the object (textfield) from the NSMutableArray it will receive a release message. So this tableviewcell will lost the reference of the textfield causing the crash.

The solution

Actually the solution is very simple. You only have to retain an reference of the object before you remove it from the NSMutableArray, then tableview will be able to do its job. See as follows:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
    if ([self.tableViewData count]>1) {
        // If row is deleted, remove it from the list.
        if (editingStyle == UITableViewCellEditingStyleDelete)
            [self.tableView beginUpdates];
            // delete your data item here
            UITextField *tf = [self.tableViewData objectAtIndex:indexPath.row];
            [tf retain];
            [tf removeFromSuperview];
            [self.tableViewData removeObjectAtIndex:indexPath.row];

            // Animate the deletion from the table.
            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
            [self.tableView endUpdates];

I hope it helps !

Asynchronous images on iOS

The iOS SDK provides many ways to manipulate images. The simplest way is loading an Image into an UIImageView. The issue of this way is that loading the image in that way is a synchronous operations:

UIImageView *imageView = [[UIImageView alloc] initWithFrame: CGRectMake(100.0, 100.0, 57.0, 57.0)];

NSData* data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"image.jpg"]];

UIImage* image = [[UIImage alloc] initWithData:data];

[imageView setImage:image];

[image release];

[data release];

When you are loading many images, synchronous operations are not your best friend because it does not have a good performance. In this case you will prefer to load the images asynchronously. To do that, you can solve the situation using threads. But I want a reusable solution based on classes, so I decide to extend the UIImage to do that.

My code is based on the code of iOS Dev Tips, but instead of use an UIImageView I decide to use an UIImage. The strategy is download the image as a NSData in background and use a delegate to notify your classe. Follow the AsynchronousUIImage.h :


@class AsynchronousUIImage;

@protocol AsynchronousUIImageDelegate


-(void) imageDidLoad:(AsynchronousUIImage *)anImage;


@interface AsynchronousUIImage : UIImage{

NSURLConnection *connection;

NSMutableData *data;


@property (nonatomic, assign) id  delegate;

@property (nonatomic)  int tag;

- (void)loadImageFromURL:(NSString *)anUrl;

The protocol has one optional method called imageDidLoad:(AsynchronousUIImage *)anImage so your code can be notified that the image has loaded. The interface has two properties one for the delegate and the other one is a tag to identification when the delegate is called.

So, let’s go to the implementation:

@implementation AsynchronousUIImage

@synthesize delegate;

@synthesize tag;

- (void)loadImageFromURL:(NSString *)anUrl {

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:anUrl]



connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];


- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {

if (data == nil)

data = [[NSMutableData alloc] initWithCapacity:2048];

[data appendData:incrementalData];


- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection


[self initWithData:data];

[data release], data = nil;

[connection release], connection = nil;

[self.delegate imageDidLoad:self];



[super dealloc];

connection = nil;

data = nil;


In the loadImageFromURL method we use NSURLConnection to get the data from the web then in the didReceiveData method we get the pieces of data and finally in the connectionDidFinishLoading method we set the data to the UIImage object, do the memory management and call the delegate method.

So, you can use AsynchronousUIImage class that way:

AsynchronousUIImage *image = [[AsynchronousUIImage alloc] init];

[image loadImageFromURL: @"http://yourimage" ];

image.tag = 1;

image.delegate = self;

[image release];

And then implement the imageDidLoad delegate method that way:

-(void) imageDidLoad:(AsynchronousUIImage *)anImage{

 if (anImage.tag == 1) {

 myImageView.image = anImage;



You can find a complete example in:

Premium Wordpress Plugin