Category Archives: objective c

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;
}

Getting NSDate from NSString

Very useful, yet short and simple, code snippet on how to rip the NSDate from NSString using NSDateFormatter:

NSString *dateString = @"2010-01-19";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
// ta-daaa!
dateFromString = [dateFormatter dateFromString:dateString];

If you need more info about different date formats see Unicode Date Format Patterns. Of course if you usually work with standard dates you can use setDateStyle instead of setDateFormat.

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/

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

Xcode Color Themes


This is a small collection of my personal preference of color themes for xcode programming environment. For those who are looking for a dark theme. You can chose from one of the following color themes. I’m currently using teliaz theme, it has been tested and works very smoothly.

To get

teliaz theme

run the following code in Terminal:

mkdir -p ~/Library/Application\ Support/Xcode/Color\ Themes; cd ~/Library/Application\ Support/Xcode/Color\ Themes; curl http://teliaz.com/files/apple/TeliazTheme.xccolortheme &> TeliazTheme.xccolortheme

To get

Ego theme

run the following code in Terminal:

mkdir -p ~/Library/Application\ Support/Xcode/Color\ Themes; cd ~/Library/Application\ Support/Xcode/Color\ Themes; curl http://teliaz.com/files/apple/XCodeColorTheme.xccolortheme &> EgoTheme.xccolortheme

“EGO” uses the font “DejaVu Sans Mono” at 12pt. Some of you may know it as “Panic Sans” from Panic’s Coda (which is a repackaged version of it). You can grab the font over at dejavu-fonts.org. If you already have Code installed, feel free to swap in Panic Sans in place of DejaVu Sans Mono.

To get

Humane Theme

run the following code in Terminal:

mkdir -p ~/Library/Application\ Support/Xcode/Color\ Themes; cd ~/Library/Application\ Support/Xcode/Color\ Themes; curl http://teliaz.com/files/apple/Humane.xccolortheme &> Humane.xccolortheme

Now just restart Xcode, go to Preferences > Fonts & Colors, and select “one of these themes” from the color theme drop down. Hope you like it!! Happy coding…

Objective C – Basic Datatypes and NSLog


Have you been frustrated sometimes trying to debug an application and really making it worse, the output of your logs are not as desired. Complete chaos and nonsense.

Some of the concepts here will be familiar in c coding language, as objective c is just an extended c with object oriented approach. Take a quick look at this table that will surely clear things up.

Type Constants NSLog Short Explanation
char "a", "\n" %c
short int %hi, %hx, %ho %hi, %hx, %ho
unsigned short int %hi, %hx, %ho %hi,
%hx (hex notation),
%ho (octa notation)
int 12, -97, 0xFFE0, 0177 %i, %x, %o also %d can be used in objective-c
unsigned int 12u, 100U, 0xFFU %u, %x, %o as above
long int 12L, -200l, 0xfffL %lu, %lx, %lo as above
long long int 0xe5e5e5e5LL, 500LL %lli, %llx, %llo as above
long long unsigned int 0xe5e5e5e5ULL, 120ULL %llu, %llx, %llo as above
float 12.34f, 3.1e-5f %f, %e, %g %f (with 6 decimal place by default),
%e (with scientific notation), %g (personal preference most readable)
double 12.34, 3.1e-5 %f, %e, %g as above
long double 12.34l, 3.1e-5l %Lf, %Le, %Lg as above
id %p