Apr
10
2011

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;
}
no comments | tags: apple, cocoa, core, data, iphone, sdk | posted in objective c
Mar
28
2011
#if ! defined(IFT_ETHER)
#define IFT_ETHER 0x6/* Ethernet CSMACD */
#endif
- (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;
}
freeifaddrs(addrs);
}
}
no comments | tags: iphone, mac address, snippet | posted in iPhone
Dec
24
2010
Coming back to the ultimate purpose of this blog… helping my memory!
Here we are: a code snippet to copy a NSString to the clipboard…
-(void)copyToClipboard:(NSString*)str
{
NSPasteboard *pb = [NSPasteboard generalPasteboard];
NSArray *types = [NSArray arrayWithObjects:NSStringPboardType, nil];
[pb declareTypes:types owner:self];
[pb setString: str forType:NSStringPboardType];
}
no comments | tags: clipboard, NSString, objective c, xcode | posted in objective c
Dec
24
2010
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.
no comments | tags: nsdate, NSString, objective c, xcode | posted in iPhone, objective c
Nov
6
2010
He is a quick way to separate iPhone 4 / iPhone 3 code snippets.
float version = [[[UIDevice currentDevice] systemVersion] floatValue];
if (version >= 3.0)
{
// add your code for iphone 4 (retina display!)
}
else
{
// add your code for iphone 3/3Gs
}
no comments | tags: iphone, objective c, version | posted in iPhone, objective c
Oct
4
2010
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…
1 comment | tags: icon, iphone, iphone 4, spotlight, touch | posted in iPhone, objective c
Jul
20
2010
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)
no comments | tags: alpine, iphone, openssh, root, winscp | posted in iPhone
Jul
8
2010
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);
}
no comments | tags: capture, image, iphone, load, objective-c, remove, save | posted in objective c, Uncategorized
Jul
8
2010

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
4 comments | tags: bug, CLLocation, CLLocationManager, didupdatetolocation, iOS4, iphone, simulator, tips | posted in objective c, Tips
Jul
3
2010

Yet another small useful collection of small code snippets for NSString.
Continue reading
no comments | tags: iphone, NSString, obective c, programmming, tip, xcode | posted in objective c