Ready to Level-Up?

This just in! If your rusty iOS skills could use some refining, or if you're just starting out and you want to level-up fast, consider signing up for our upcoming iOS Screencasts

New from iOS Rocket Surgery Swift Video Tutorials: The rapidly evolving Apple-iOS ecosystem has just been thrown into tumult with the recent introduction of the Swift Programming Language. Are you ready to finally try iOS development? Are you needing to switch from Objective-C to Swift? Sign up today for our free video courses!
(By the dear folks at Swift Tutorial Videos, a sister company)

Tuesday, October 16, 2012

Settting a Background Image on a UIView in iOS

How to Set the Background Image of a UIView

// Oddly, we set the background to be a color, with the image applied as a pattern
UIColor *bg= [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"myimg.png"]];

// Then we just set the background to be our new color on whatever UIView we want to.
// Here, I am assuming you are inside of a UIView
self.view.backgroundColor = bg;

Note: If you're getting a black background image instead of the image you expected, then check to make sure that you've added the image file to your project, and didn't just copy to the project folder on the filesystem. Use "Add File to ___ ..." to include the image in your project.

Read More

Wednesday, October 3, 2012

Deleting an NSManagedObject

How to Delete an NSManageObject in iOS Core Data...

// Lets assume we already have a manage object context ... from our created database

// we'll call managedDatabaseObject
NSManagedObjectContext *context = managedDatabaseObject.managedObjectContext;

// So, well create a request to fetch our Person we wish to delete
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];

// And we'll filter our request by the person id we have on hand (assumedly) 
NSPredicate *predicate = [NSPredicate predicateWithFormat: @"id = %@", personId];
[request setPredicate:predicate];

// And we have to specify a sortDescriptor every time we fetch, regardless
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"last_name" ascending:YES];
[request setSortDescriptors:@[sortDescriptor]];

NSError *error;
NSArray *results = [moc executeFetchRequest:request error:&error];

if (results == nil)
    // Deal with error...
} else {
  NSManagedObject *person = [results lastObject];
  [context deleteObject:person];

Read More

Popup Alert Message in iOS

How to Show a Popup Alert Message Dialog Box (UIAlertView) in iOS...

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"There was a problem" message:@"The problem was serious, press OK to close this message." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];

[alert show];

Read More

Tuesday, October 2, 2012

Fetching a Core Data Record in iOS

// Lets start by creating a NSFetchRequest object that we will use to access the db.
// In this particular case, we have a Core Data Entity (ie. model/table) with the 
// name of 'Person'
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];

// Next, lets specify the filter criteria that we'll use to fetch our record(s)
// Here, we're basically saying "fetch people records with the last name of 'Walker'"
request.predicate = [NSPredicate predicateWithFormat:@"last_name = %@", @"Walker"];

// Next, we'll specify the order that the records should be returned into our array
// In this case, I want the order of results to be returned in last-name ascending order
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"last_name" ascending:YES];

// And now we'll just add the sort descriptor to the request
request.sortDescriptors = [NSArray arrayWithObject: sortDescriptor];

// Here, we'll set aside a reference to capture any errors that occur during a fetch    
NSError *error = nil;

// And here, we'll execute our fetch
NSArray *results = [context executeFetchRequest:request error:&error];

// Make sure we got some results
if(! results || ([results count] == 0)){
  // handle this in your particular fashion
} else {
  // Ok, now because the result set is just an array, we can grab any of the items 
     // at any index we want. But, I'm expecting there to be 1 result anyway so...

  NSObject *person = [results lastObject];

// And, yes, I could/should show you how to log the error, if any
if (error) {
  NSLog(@"Error: %@", error.localizedDescription);

Read More

A Simple Table View Controller Example

// Ok, so lets imagine that I have a view, a storyboard and our view wants to display
// a list of people, then when a list item is clicked on, we want to segue to a details
// page. With this assumption, lets assume I have setup the Person entity as well.

#import "MyTableViewController.h"
#import "Person.h"

// To make my life even easier, I am going to assume you're using CoreDataTableViewController 
// which is a class available from the Standford cs193p iOS development class.
// I'll add a link later

@implementation MyTableViewController

// So, in a previous post, I showed you how to obtain a managed document object that would
// allow you to access the database, so I'm not going to repeat that, but instead I'm going
// to assume that another controller is handing you a database managed document object
// that is already initialized and ready to go.
@synthesize myDatabase = _myDatabase;

// And this is where we are being handed the database object reference
-(void) setPromotionsDatabase:(UIManagedDocument *)promotionsDatabase
  _promotionsDatabase = promotionsDatabase;

// So, thanks to that other controller, we have a database object we can work with, so now
// all we need to do to display data is to set a NSFetchedResultsController instance
// with the right filters and such to pull the Person data we want.
// Here, we're relying heavily on the CoreDataTableViewController to implement some 
// extra Protocol cruft for us, so we can focus on accessing the data.
// Some day, I'll implement a full example.

// Anyway, we want to display the core data Person entity data in our table, so we need
// so create a NSFetchedResultsController for that purpose...

-(void) setupFetchedResultsController
    // Create a data fetch request to pull some Person entity data from the core data tables
  NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];

    // We want to sort by last name (a column in the Person table) in ascending order
  request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"last_name" ascending:YES]];

    // Now we instantiate a NSFetchedResultsController by handing it our request in its init
    // blog, and therefore our obligation for determining how to fetch the data for the 
    // table to display is basically complete.
  self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.promotionsDatabase.managedObjectContext sectionNameKeyPath:nil cacheName:nil];

// Lets be sure to set that NSFetchedResultsController right before we show the screen
// so it will start fetching data as the screen is getting ready to load.

- (void) viewWillAppear:(BOOL)animated
    [super viewWillAppear:animated];
    [self setupFetchedResultsController];    

// Ok, we've taken care of getting data to the table, but we haven't done much about saying
// what to display in the table...
// So, we implement the cellForRowAtIndexPath method like so...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    // Now, bear with me, but basically, you need to set an unique identifier for a cell
    // in your Xcode UI designer on your table cell rendering element... won't go into detail
    // on that right now.
  static NSString *CellIdentifier = @"Person Cell";

    // So, now get the cell object that we will use to render the row 
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    // Ok, here's a cool thing... since we taught the table how to fetch data using
    // the above NSFetchedResultsController, the data is there already and we can just
    // fetch the row that corresponds to the current row-cell we are rendering
  Person *person = [self.fetchedResultsController objectAtIndexPath:indexPath];
    // We set the text label and the detail label (assuming that is the kind of cell we 
    // are rendering with
  cell.textLabel.text = person.last_name;
  cell.detailTextLabel.text = person.age;
    // All done, the row will be rendered.
  return cell;

// Ok, lets also assume we dragged our cell onto another view controller and created a PUSH 
// segue, I know we're doing a lot of assuming, but bear with me

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    // Get the cell that was clicked and the person that corresponds to that rendered cell
  NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
  Person *person = [self.fetchedResultsController objectAtIndexPath:indexPath];
    // If possible, hand the person object off to the controller we are segueing to... 
    // that controller must implement the setPerson method to make that happen
  if([segue.destinationViewController respondsToSelector:@selector(setPerson:)]){
        [segue.destinationViewController setPerson:person];


// I'll followup later by clarifying assumptions and providing the CoreDataTableViewController implementation you need to get going.

Read More

About Me

Easy NSDateFormatter Tool

Save yourself some time in formatting your NSDates to NSStrings, and use the Blind NSDate app, which you can download from iTunes. There's also a website where you can format your NSDates:

Popular Posts

Designed By Seo Blogger Templates