iPhone / Objective-C Code Examples (and .NET equivalents)

I have found myself reusing a lot of the same code throughout my apps. I thought I would publish some tips and code snippets to hopefully get you going on your next project. Here they are, in no particular order. I also tried to put a .NET equivalent for those of you who, like me, are coming from a long .NET background.


1) Use NSLog liberally to debug as you write your code. You can really do a lot with it. A few standard statements are for printing strings or numbers, and you can also print an Objective-C object. Here are the three I use most often:


NSLog(@"%@", aString); // prints any NSString, for example
NSLog(@"%d", anInt); // prints a signed int
NSLog(@"%f", aFloat); // prints a float



2) If you have a UITableView that you need to have updated, you can reload it with this command (assuming it is named "tableView"):


[self.tableView reloadData];



3) Need to iterate through a collection? Try this handy code snippet, which is similar to For Each in .NET languages:


for (id currentObject in allObjects) {
// do something here with currentObject
}



4) Here is how you can check to see if an object is certain type. This is a bit like using gettype or typeof in .NET to find a specific type:


if ([myObject isKindOfClass:[TheClassIAmLookingFor class]]) {
}



5) Here is how you cast an object in Objective-C, like using CType or DirectCast in .NET:


TypeToCastTo typeCastObject = (TypeToCastTo *)myObject;



6) I show alert pop-ups a lot in my apps. Here is a simple example for an alert launched when a button is clicked, and responded to to perform some action.


-(void)resetClicked:(id)sender withEvent: (UIEvent *) event {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Reset" message:@"Are you sure you want to reset this puzzle?\nAll of your work will be lost!" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
[alert show];
[alert release];

}

- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
// the user clicked the OK button
if (buttonIndex == 1)
{
// reset logic goes here

}

}



7) Split is a great function in .NET. Here is the Objective-C equivalent:


NSArray *arrayOfValues = [commaDelimitedListOfValues componentsSeparatedByString:@","];



More code snippets next time! Good luck!

0 comments:

Post a Comment