Tag Archives: iphone

Coredata Resource Links


Apple resource

Apple’s Core Data Programming Guide

Efficiently Importing Data

Apple guideline to import data

Cocoa is my Girlfriend

Super easy Fetching Core Data

Cocoa with Love

Core Data Line Fetch

Cocoa Dev Central

nice article with example structure and images

Import Data to CoreData Project

  • Create the model in XCode (it is essential do this first, because XCode uses a specific naming convention and adds several underlying tables to the actual data model.
  • Run the application in the Simulator and with the app running … go and copy the database (/users/library/Application Support/iPhone Simulator/User/Applications/ to some other location
  • Open up the database (I use SQLite Manager plugin in Firefox)
  • From here I import my data from a CSV file once I have updated all of my CSV column names to match the table names
  • Look at the CoreDataRecipies sample code for including a pre-populated database (code is in the Delegate.m file)
  • Import the database in your application and you should be good to go.
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
	NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"Recipes.sqlite"];
	 Set up the store.
	 For the sake of illustration, provide a pre-populated default store.
	NSFileManager *fileManager = [NSFileManager defaultManager];
	// If the expected store doesn't exist, copy the default store.
	if (![fileManager fileExistsAtPath:storePath]) {
		NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"Recipes" ofType:@"sqlite"];
		if (defaultStorePath) {
			[fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
	NSURL *storeUrl = [NSURL fileURLWithPath:storePath];
	NSError *error;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
		// Handle error
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		exit(-1);  // Fail
    return persistentStoreCoordinator;

iPhone Wifi MacAddress

#if ! defined(IFT_ETHER)
     #define IFT_ETHER 0x6/* Ethernet CSMACD */

- (IBAction)testAction:(id)sender
      #pragma unused(sender)
      BOOL                              success;
      struct ifaddrs *               addrs;
      const struct ifaddrs *           cursor;
      const struct sockaddr_dl *      dlAddr;
      const uint8_t *               base;
      int                              i;

      success = getifaddrs(&addrs) == 0;
      if (success) {
          cursor = addrs;
          while (cursor != NULL) {
               fprintf(stderr, "%s\n", cursor->ifa_name);
               if ( (cursor->ifa_addr->sa_family == AF_LINK)
               && (((const struct sockaddr_dl *) cursor->ifa_addr)->sdl_type == IFT_ETHER) ) {
               dlAddr = (const struct sockaddr_dl *) cursor->ifa_addr;
               fprintf(stderr, " sdl_nlen = %d\n", dlAddr->sdl_nlen);
               fprintf(stderr, " sdl_alen = %d\n", dlAddr->sdl_alen);
               base = (const uint8_t *) &dlAddr->sdl_data[dlAddr->sdl_nlen];
               fprintf(stderr, " ");
               for (i = 0; i < dlAddr->sdl_alen; i++) {
                    if (i != 0) {
                    fprintf(stderr, ":");
                    fprintf(stderr, "%02x", base[i]);
               fprintf(stderr, "\n");
               cursor = cursor->ifa_next;


iPhone Touch Icon – Create your own Icon Set

Since the introduction to the iPhone 4, we now have some additional icons we need to create to support the Hi-Res graphics of the iPhones Retinal Display. Altogether we now have a total of 6 app icons, each with a different pixel size in order to support all devices they are as follows:

  • iPhone 4 Hi-Res App Icon ( 114 x 114 )
  • iPhone App Icon ( 57 x 57 )
  • iPad App Icon ( 72 x 72 )
  • iphone 4 Hi-Res Spotlight Icon ( 58 x 58 )
  • iPhone Spotlight Icon ( 29 x 29 )
  • iPad Spotlight Icon ( 50 x 50 )

After recently developing a few iPhone apps, I found it to be a redundant task to create 6 icons every time I make a new app. To make this process faster, I’ve created a PHP script that takes the highest resolution icon and converts it down to the 6 icons required.
You can find this script at my company website at http://empoc.com/ios-icons/
It only takes a few seconds to create all of the icons and when the script has finished running you will be able to download them all in a nicely zipped up file. I’ve also got instructions there that will show you what to do with the icons once you’ve downloaded them.
Please have a look and let me know what you think…

Alternatively you can visit make app icon to create the whole set of icons http://makeappicon.com/

Wiscp on iPhone

First make sure you have ssh and bsd subsystem installed from installer. If you cant find the source reboot or turn off wifi and back on.

Next get WinSCP and find your iPhone’s ip by going to (on your iphone) settings > Wi-Fi > “Your selected WiFi” > Look under IP Address- Connect to your iPhone using WinSCP (user: root password: alpine) Change File Protocol to SCP.

Once OpenSSH is installed your phone will be vunerable to all users in a specific wifi subnet. Make sure to Use the WinSCP terminal window an use this command to change password:

passwd root
type in password, press return
type it in again, press return

To avoid frequent logouts remember to change the Setting -> General -> Auto-Lock (5 minutes or Never)

Capture Save/Load/Remove Image in documents directory

NSFileManager offers a convenient way to write images to and load them from the documents directory.
If you’re frequently doing that in your project, I suggest to wrap up NSFileManager support in three simple methods:

Save/Load/Remove Image Methods

//saving an image

- (void)saveImage:(UIImage*)image:(NSString*)imageName {

NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.

NSFileManager *fileManager = [NSFileManager defaultManager];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]];

[fileManager createFileAtPath:fullPath contents:imageData attributes:nil];

NSLog(@"image saved");


//removing an image

- (void)removeImage:(NSString*)fileName {

NSFileManager *fileManager = [NSFileManager defaultManager];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", fileName]];

[fileManager removeItemAtPath: fullPath error:NULL];

NSLog(@"image removed");


//loading an image

- (UIImage*)loadImage:(NSString*)imageName {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]];

return [UIImage imageWithContentsOfFile:fullPath];


Now, you can easily save an image like:

[self saveImage: myUIImage: @"myUIImageName"];

or load it like:

myUIImage = [self loadImage: @"myUIImageName"];

or remove it like:

[self removeImage: @"myUIImageName"];

Capture an image

– (UIImage*) getGLScreenshot {
NSInteger myDataLength = 320 * 480 * 4;

// allocate array and read pixels into it.
GLubyte *buffer = (GLubyte *) malloc(myDataLength);
glReadPixels(0, 0, 320, 480, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

// gl renders “upside down” so swap top to bottom into new array.
// there’s gotta be a better way, but this works.
GLubyte *buffer2 = (GLubyte *) malloc(myDataLength);
for(int y = 0; y <480; y++) { for(int x = 0; x <320 * 4; x++) { buffer2[(479 - y) * 320 * 4 + x] = buffer[y * 4 * 320 + x]; } } // make data provider with data. CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer2, myDataLength, NULL); // prep the ingredients int bitsPerComponent = 8; int bitsPerPixel = 32; int bytesPerRow = 4 * 320; CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault; CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault; // make the cgimage CGImageRef imageRef = CGImageCreate(320, 480, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent); // then make the uiimage from that UIImage *myImage = [UIImage imageWithCGImage:imageRef]; return myImage; } - (void)saveGLScreenshotToPhotosAlbum { UIImageWriteToSavedPhotosAlbum([self getGLScreenshot], nil, nil, nil); } [/sourcecode]

CLLocationManager delegate method is not called in iOS4

Weird bug-easy solution.
I did have this weird issue also when updating to SDK4.0. I couldn’t get CLLocationManager to work on simulator. This problem also existed in iPhone Simulator 3.1.3.

The solution is quite weird. Open the Airport (wifi) in your mac and the CLLocationManager will work as before fetching the Cupertino, or in my case fetching a wide area of my country.
I guess the Location is estimated by the internet ip address of your connection.

Continue reading CLLocationManager delegate method is not called in iOS4

NIBs or code? Why not both? Here’s nib2objc.

(Somehow this project seems to me so simple, that I’m sure someone has done this before. Anyway). This is my feeble attempt to bring an answer to the eternal dichotomy between those arguing about the relative benefits of creating user interfaces via Interface Builder or via pure Objective-C code: let me introduce nib2objc.
Continue reading NIBs or code? Why not both? Here’s nib2objc.

Trace freed/deallocated instances of objects

This procedure has saved me more than once, so I need to document it throughly for everyone! There are cases where I see messages (in the debugger console) that are like this;

 >-[NSFetchedResultsController class]: message sent to deallocated instance 0x11957d0

Sometimes, it will talk about “freed” instead of deallocated. That address at the end is important. To track down the line of code where the object was allocated, you’ll need to set a couple environment settings. To do this, right click on the executable you’re trying to debug and select “get info”. Select the “arguments” tag and set the values shown below;

MallocStackLoggingNoCompact 1

NSZombieEnabled YES

debug environment settings

(be sure to disable these when you’re done. They should not be enabled for a production build!)

Next, run your program and test enough to generate the error. In the Debugger Console, copy that hex address value, then type the command;

(gdb) info malloc-history <paste-address-here>

You should see something like this;
Stack – pthread: 0xa0416720 number of frames: 28
0: 0x9264382d in malloc_zone_calloc
1: 0×92643782 in calloc
2: 0×93611618 in _internal_class_createInstanceFromZone
3: 0x9361ab08 in _internal_class_createInstance
4: 0x3020275c in +[NSObject allocWithZone:]
5: 0x3020264a in +[NSObject alloc]
6: 0x3d92 in -[AMRAPViewController fetchedResultsController] at /Users/dkavanagh/CrossFit Timer/Classes/AMRAPViewController.m:146
7: 0x3a18 in -[AMRAPViewController viewWillAppear:] at /Users/dkavanagh/CrossFit Timer/Classes/AMRAPViewController.m:96
8: 0x3097c945 in -[UINavigationController _startTransition:fromViewController:toViewController:]
9: 0x30977c33 in -[UINavigationController _startDeferredTransitionIfNeeded]
10: 0x3097d01e in -[UINavigationController pushViewController:transition:forceImmediate:]

The first line below the object alloc (in my case, line 6) will show where the offending object was allocated and should really help in tracking down the free/dealloc problem.