iMy Objective-C / iPhone App Development FAQ

Organizing ones learned lessons does not take much effort. The key is consistency, documenting things in a common mode (such as a binder, or a small note book, etc.). For decades I have preferred to use small bound ‘journal’ type books. Once full, the retire to my book-case for future reference. They have been incredibly useful over the years, holding esoteric bits of data generally accessible by myself recalling the rough dates I wrote relevant code, or learned a new programming language, reference that with the dated pages in the books (I ALWAYS date the pages in my notebooks) and voila.. if I had a personal epiphany, I recorded it there.

This time, I’m trying something a little different. Taking those same notes, but this time making them public for others to hopefully gain from the things I’ve learned. So, on with the show.


Creating a multi-line NSString object

If you have battled with maintainability in long NSStrings, I found the simple solution. Oddly, a couple of hours searching on the web did not even get close to showing me this. I just used some old C language line continuation syntax, figured out how Objective-C like to do it, and voila…, problem solved.

It’s quite simple really. The trick is the slash right after the closing double-quote. If you have whitespace, iOS 4.x will nick you with a warning. It still compiled and ran, but a warning is there for a reason, and this syntax throws none.

As with all these sorts of posts, I hope it helps someone else.

		NSString* appStoreLink = @"http://itunes.apple.com/us/app/icidr/id400066695?mt=8&ign-mpt=uo%3D4";
		NSString* msg = [NSString stringWithFormat:\
					 @"Check out this cool App I found in the App Store!\n"\
					 "\n"\
					 "%@ helps you understand CIDR Block IP notation.  It's packed with some great "\
					 "features I think you'll find very useful.\n"\
					 "\n"\
					 "Version %@ of %@ is available now, just follow this App Store for more information:\n"\
					 "%@"\
					 ,appName
					 ,version
					 ,appName
					 ,appStoreLink];

yes, that’s REAL code from one of my apps.

Dismissing a Keyboard after UITextField input

Strategy entails using the keyboards ‘Return’ key to signal that one is done. Seems useful, but only if you have a single line text input. In my case, that’s what I’m looking at, single line input, so that’s the solution I’m going to try.

First things first, rename the Return key to Done. Ah… so now you see how to prompt the user to hit the enter key when they are ‘Done’. Tricky. Dirty-tricky? Maybe, but it will work.

WAS:

This is accomplished by changing the ReturnKey property dropdown available in the UITextField property inspector. The dialog looks like this:

Dialog dropdown to change the 'Return' key to 'Done'

NOW:

OK, that was the EASY part… the next part requires cutting some code, over-riding some methods and thinking a few things through.

The tricky part is understanding that you need to make sure your object has implemented UITextFieldDelegate. This is how that might look:

@interface seeView : UIViewController <UITextFieldDelegate> {
    UITextField* seeTextField;
}

Following that you’ll need to enable viewDidLoad (boilerplate code) and implement some delegation:

- (void)viewDidLoad {
	
	UITextField *seeText = (UITextField *) [self.view viewWithTag:102];  // try to locate the object with the tag
	seeText.delegate = self;  // assign a delegation.
	[super viewDidLoad];
}

But the fun is not quite over yet.. The textFieldShouldReturn method will need to be defined to execute the abandonment of the first responder:

// Should trap all Keyboard Return Events
- (BOOL) textFieldShouldReturn:(UITextField*)textField {
    [textField resignFirstResponder]; 
    return YES;
}

You also need to know something about wiring classes and the File Owner together in the relevant Nib file. But you know how that plays out already, right?

UPDATE: 19-NOV-2010

After banging my head into the table for, uh, about 3 hours trying to get the ‘viewDidLoad‘ method to fire off… while digging around in the dusty corners of sites.. I FINALLY found THE ANSWER to this dilema. So.. now I’m going to add it in here so I don’t effing for get as well!!!

Make sure your Tabs have the type set to the NIB type NOT UIViewController!


Display only numbers for certain keyboard events

It turns out this was just as easy as changing the Return button on the main keyboard to read Done. The same dropdown is play. The option I selected was Numbers and Punctuation. It looks like this:

Keyboard after changing the property to 'Numbers & Punctuation'


Dismissing the Keyboard after any Button Press

** This is the 3rd thing I need to tackle. First I have to get some math stuff ironed out and tested, as well as some more advanced string deconstruction and manipulation. This will be an important thing to get worked out, since the keyboard will cover 1/2 my UI but the main button is still visible, meaning people will hit that instead of closing the keyboard first. That needs to be taken into consideration and coded for. People don’t want to click twice when they can click once. Seems pretty logical to me.


Regular Expression Solutions

About 8 hours of hunting, hacking, a little screaming and finally some yelling in rejoice.. I have sorted out, FINALLY a simple, contained example of Regular Expression executing in Objective-C. This may for work you, it may not. It might not have the error control you like, well.. you’re getting it for free so.. don’t get too worked up about it.

Basically, you’re going to need to use the regex.h C libraries to get it done. The upside is that it’s already on your system. Here is the snipped of code that I used to do some regexing on a string. Obfuscated since I’m not going to show exactly what I’m doing (oops.. my tin hat almost fell off). I’ve added a few comments. Now.. how did I learn this? By a lot of trial and error, frustrated looks at ‘iPhone Cookbooks’ that are so out of date 1/3 of the code is depricated… and then.. I found this little gem: Advanced Strings In Cocoa
so most of the credit goes to those that went before I.

- (BOOL)validateString:(NSString*)seeStr {
	// Take the textField apart into pieces for computation
	NSString* pattern = @"^[:character:]$";
	NSString* result = nil;

	regex_t preg;
	int err = regcomp(&preg,[pattern UTF8String],REG_EXTENDED);	
	if(err) {
		char errbuf[256];  // This was the biggest mistake I was making, not using CHAR here
		regerror(err,&preg,errbuf,sizeof(errbuf));
		UIAlertView *av = [[[UIAlertView alloc] initWithTitle:@"Internal Error" message:@"ERROR Code 17" delegate:nil cancelButtonTitle:@"OK"otherButtonTitles:nil] autorelease];
		[av show];
		[NSException raise:@"CSRegexException" format:@"Could not compile regex %@: %s",pattern,errbuf];
	}
	
	const char *cstr=[seeStr UTF8String];  // This is another important bit of casting
	regmatch_t match;
	if(err = regexec(&preg,cstr,1,&match,0)==0){
		result = [[[NSString alloc] initWithBytes:cstr+match.rm_so length:match.rm_eo-match.rm_so encoding:NSUTF8StringEncoding] autorelease];
//		UIAlertView *av = [[[UIAlertView alloc] initWithTitle:@"MATCH!!!" message:result delegate:nil cancelButtonTitle:@"OK"otherButtonTitles:nil] autorelease];
//		[av show];
		return YES;
	}
	else {
		char errbuf[256];
		regerror(err,&preg,errbuf,sizeof(errbuf));
//		[NSException raise:@"CSRegexException" format:@"Could not complete a match %@: %s",pattern,errbuf];
		return NO;
	}

It worked like a charm, I used a very complex pattern (not shown here) for a long string validation and it was spot on. And quick. And it worked. I hope this helps someone.


String Splitting

It turns out that slitting strings is Pretty Easy, or at least a lot easier that I had expected. This is a part of my daily programming life.. string manipulation… and one of those most common manipulations are splitting things apart into arrays for iterative processing.

So.. how hard is it to do in Objective-C? Not had at all, in fact, it’s all that it takes!

NSString *msg = @"The Dog/Cat is lazy";   //  included here for context of msg
NSArray *parts = [[NSArray alloc] initWithArray:[msg componentsSeparatedByString:@"/"]];

Yeap.. that’s all it takes!!

Now let’s say the string was this: “The Dog/Cat is lazy”. And I want to get the first ‘part’ of that sentence, the part before the ‘/’. It’s as easy as pie (based on the line of code above):

NSString *aboutDog = [parts objectAtIndex:0];

So the variable aboutDog would contain the string at the first index (indexes start at 0 but you know that, because you’re not a sap developing for Windoze) and the value there is… TADA… The Dog. Fun. Easy… and if you know the index count (working on that) you can build a simple loop to do whatever you want!


NSString to Integer

The pain of robust variable casting… means you can’t be PERL/PHP lazy with your variables… you’d better know what you are putting in there, or where you are using it. So.. sometimes you feel like a nut uh.. string, and some times you don’t. Today I didn’t so off with it’s head! Sorta..

In this little story.. the string is named parts and I’m going to make a copy of it in the form of an integer with the name bits. So.. there you have my parts and bits all laid out for you to see (and if you’re a cute girl under 40, and you like what you see, give me a ring… uh huh). Uh.. digressing.. yeah.. code. Sorry. So that’s all there is to it. You’re welcome.

int      bits     = [[parts objectAtIndex:1] intValue];


Objective-C Math – just the basics Mama


App Store and Device Icon General Recommendations

General .png image sizes for Apple iPhone / iPad / iPod Apps:

App Store 512×512
.png
App Store Artwork Size (512 x 512)
App Icon 57×57
.png
App Icon
Spotlight Icon 29×29
.png
Spotlight

Add a line to UI View with UI Builder

Seems like a simple enough thing to handle, but I don’t see any elements that would provide this function.


Sending Things off to e-Mail Helper App

I finally had time to dig into this and find out how to make it all work.

There are a few things you must do to get In-App e-mail working. The first of which is to Add the Mail Framework to your set of frameworks. See the screen snipped here. The one you want is UIMessageFramework:

Once that has been added to your Framework, the fastest road to deployment that I found was to add the function right into the view you’re working with. Sure, it’s better from the statndpoint of pure OO programming to class this out, but I have a simple tool (from the standpoint of the UI, it was not simple for me to write the mathy bits) and it does not warrant strict OO policy enforcement.

So.. I just added the following (bold) to my View’s header file:

#import <UIKit/UIKit.h>
#import <MessageUI/MFMailComposeViewController.h>

@interface iCIDRViewController : UIViewController <UITextFieldDelegate, MFMailComposeViewControllerDelegate>  {

With the required framework referenced and appropriate delegation added, it’s off the the main code (.m) file.

You will need this block of code for the mail controller. Good news is that the SDK IDE will basically write the entire method for you, just need to add braces and you’re off:

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
	[controller dismissModalViewControllerAnimated:YES];
}

Finally, you write the bits for sending the mail. How you call this, is up to you. I used a ToolTab Navigation button to trigger it. Do as you please. As a bonus, I top my hand on multi-line (visually) singular NSString construction. Here is where the rubbers meet the roadies:

- (IBAction)shareApp:(id)sender {
	MFMailComposeViewController *picker = 
	[[MFMailComposeViewController alloc] init];
	picker.mailComposeDelegate = self;
	
	NSString* appStoreLink = @"http://itunes.apple.com/us/app/icidr/id400066695?mt=8&ign-mpt=uo%3D4";
	NSString* msg = [NSString stringWithFormat:\
					 @"Check out this cool App I found in the App Store!\n"\
					 "\n"\
					 "Version %@ of %@ is available now, just follow this App Store for more information:\n"\
					 "%@"\
					 ,@"1.0"
					 ,@"iCIDR"
					 ,appStoreLink];
	[picker setSubject:[NSString stringWithFormat:@"Check out this cool App I found (%@)",appName]];
	[picker setMessageBody:msg isHTML:NO]; 
	[self presentModalViewController:picker animated:YES];
	[picker release];
}


Random Character String Generation

Crude but effective. I know there has to be a better way to do this, but for today, for now, for the moment, it’s going to be this:

NSString *pool = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

-(NSString *) genString: (int) len {

    NSMutableString *rand = [NSMutableString stringWithCapacity: len];

    for (int i=0; i

One thought on “iMy Objective-C / iPhone App Development FAQ”

  1. RE:iMy Objective-C / iPhone App Development FAQDavid DeMartini actual | David DeMartini actual Валок GregoireBesson Курлово

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.