Monday, July 20, 2009

Refactoring Nav from Chapter 9

I received an interesting question (in the form of a tweet) today about Chapter 9. An observant reader asked if there was a way to "DRY" (Don't Repeat Yourself) the code where we add all the controllers to the array that drives the root view controller's table, this code here:

- (void)viewDidLoad {
self.title = @"First Level";
NSMutableArray *array = [[NSMutableArray alloc] init];

// Disclosure Button
DisclosureButtonController *disclosureButtonController =
[[DisclosureButtonController alloc]
initWithStyle:UITableViewStylePlain]
;
disclosureButtonController.title = @"Disclosure Buttons";
disclosureButtonController.rowImage = [UIImage
imageNamed:@"disclosureButtonControllerIcon.png"]
;
[array addObject:disclosureButtonController];
[disclosureButtonController release];

// Check List
CheckListController *checkListController = [[CheckListController alloc]
initWithStyle:UITableViewStylePlain]
;
checkListController.title = @"Check One";
checkListController.rowImage = [UIImage imageNamed:
@"checkmarkControllerIcon.png"
]
;
[array addObject:checkListController];
[checkListController release];

// Table Row Controls
RowControlsController *rowControlsController =
[[RowControlsController alloc]
initWithStyle:UITableViewStylePlain]
;
rowControlsController.title = @"Row Controls";
rowControlsController.rowImage = [UIImage imageNamed:
@"rowControlsIcon.png"
]
;
[array addObject:rowControlsController];
[rowControlsController release];


// Move Me
MoveMeController *moveMeController = [[MoveMeController alloc]
initWithStyle:UITableViewStylePlain]
;
moveMeController.title = @"Move Me";
moveMeController.rowImage = [UIImage imageNamed:@"moveMeIcon.png"];
[array addObject:moveMeController];
[moveMeController release];

// Delete Me
DeleteMeController *deleteMeController = [[DeleteMeController alloc]
initWithStyle:UITableViewStylePlain]
;
deleteMeController.title = @"Delete Me";
deleteMeController.rowImage = [UIImage imageNamed:@"deleteMeIcon.png"];
[array addObject:deleteMeController];
[deleteMeController release];

// President View/Edit
PresidentsViewController *presidentsViewController =
[[PresidentsViewController alloc]
initWithStyle:UITableViewStylePlain]
;
presidentsViewController.title = @"Detail Edit";
presidentsViewController.rowImage = [UIImage imageNamed:
@"detailEditIcon.png"
]
;
[array addObject:presidentsViewController];
[presidentsViewController release];

self.controllers = array;
[array release];
[super viewDidLoad];
}

It's a good spot. This is, in fact, a prime candidate for refactoring. Notice how similar all the chunks of code are. With the exception of the controller class, title, and image name, each chunk of code is basically identical.

The answer to whether this can be DRY'ed, yes. This can be refactored in Objective-C and probably should. We didn't do it in the book basically because Chapter 9 was already long enough without having to use Class objects or the Objective-C runtime, and we were concerned this would add something confusing to an already long and difficult chapter.

But, my blog doesn't have to be only beginner friendly, so let's look at how we could refactor this chunk of code. First and foremost, let's start by changing the controllers property from an NSArray to an NSMutableArray so its contents can be modified by an instance method.

#import <Foundation/Foundation.h>


@interface FirstLevelViewController : UITableViewController {
NSMutableArray *controllers;
}

@property (nonatomic, retain) NSMutableArray *controllers;
@end


Next, we can create a method that will add a controller to that array. Since the items that are not the same between the various chunks of code are the controller class, the title, and the image name, we need the method to take arguments for each of those.

If we know and have access at compile time to all the classes that we will be using, we can do this pretty easily by creating a method that takes a Class object. This is the object that represents the singleton meta-object that exists for every Objective-C class. When you call a class method, you are actually calling a method on this object and you can call class methods on Class objects. So, in this scenario where we know all the classes we'll be using, we can write this method:

- (void)addControllerOfClass:(Class)controllerClass usingTitle:(NSString *)title withImageNamed:(NSString *)imageName {
SecondLevelViewController *controller = [[controllerClass alloc] initWithStyle:UITableViewStylePlain];
controller.title = title;
controller.rowImage = [UIImage imageNamed:imageName];
[self.controllers addObject:controller];
[controller release];
}

We create an instance of the correct class by calling alloc on the Class object, which returns an instance, which we can then initialize ordinarily. We declare this an instance to be the abstract superclass of all the second level controllers, SecondLevelViewController, which allows us to use both the title and rowImage properties without having to typecast or set the values by key.

Then, our viewDidLoad method becomes much, much shorter and without all the repeated code:

- (void)viewDidLoad {
self.title = @"First Level";
NSMutableArray *array = [[NSMutableArray alloc] init];
self.controllers = array;
[array release];

[self addControllerOfClass:[DisclosureButtonController class] usingTitle:@"Disclosure Buttons" withImageNamed:@"disclosureButtonControllerIcon.png"];
[self addControllerOfClass:[CheckListController class] usingTitle:@"Check One" withImageNamed:@"checkmarkControllerIcon.png"];
[self addControllerOfClass:[RowControlsController class] usingTitle:@"Row Controls" withImageNamed:@"rowControlsIcon.png"];
[self addControllerOfClass:[MoveMeController class] usingTitle:@"Move Me" withImageNamed:@"moveMeIcon.png"];
[self addControllerOfClass:[DeleteMeController class] usingTitle:@"Delete Me" withImageNamed:@"deleteMeIcon.png"];
[self addControllerOfClass:[PresidentsViewController class] usingTitle:@"Detail Edit" withImageNamed:@"detailEditIcon.png"];

[super viewDidLoad];
}

But, what if you don't know all the classes at compile time? Say, if you want to create a generic class to go into a static library? You can still do it, but you lose the compile-time check for the class and have to use an Objective-C runtime method to derive a Class object from the name of the class. Easy enough, though. Under that scenario, here's our new method:

- (void)addControllerOfName:(NSString *)controllerClassName usingTitle:(NSString *)title withImageNamed:(NSString *)imageName {

Class controllerClass = objc_getClass([controllerClassName UTF8String]);
SecondLevelViewController *controller = [[controllerClass alloc] initWithStyle:UITableViewStylePlain];
controller.title = title;
controller.rowImage = [UIImage imageNamed:imageName];
[self.controllers addObject:controller];
[controller release];
}

Notice that the only difference is that we take an NSString * parameter rather than a Class parameter, and then we get the correct Class object using the Objective-C runtime function called objc_getClass(). This function actually takes a C-string, not an NSString, so we get a C-string using the UTF8String instance method on our NSString.

In this case, we have to change our viewDidLoad method slightly to pass string constants, rather than Class objects:

- (void)viewDidLoad {
self.title = @"First Level";
NSMutableArray *array = [[NSMutableArray alloc] init];
self.controllers = array;
[array release];

[self addControllerOfName:@"DisclosureButtonController" usingTitle:@"Disclosure Buttons" withImageNamed:@"disclosureButtonControllerIcon.png"];
[self addControllerOfName:@"CheckListController" usingTitle:@"Check One" withImageNamed:@"checkmarkControllerIcon.png"];
[self addControllerOfName:@"RowControlsController" usingTitle:@"Row Controls" withImageNamed:@"rowControlsIcon.png"];
[self addControllerOfName:@"MoveMeController" usingTitle:@"Move Me" withImageNamed:@"moveMeIcon.png"];
[self addControllerOfName:@"DeleteMeController" usingTitle:@"Delete Me" withImageNamed:@"deleteMeIcon.png"];
[self addControllerOfName:@"PresidentsViewController" usingTitle:@"Detail Edit" withImageNamed:@"detailEditIcon.png"];

[super viewDidLoad];
}


Either of these options will be much easier to maintain and extend than the version in the book. You should be on the lookout for refactoring opportunities in your own code, as well. Sometimes an ounce of refactoring can save a pound of headache down the line.

Friday, July 17, 2009

Fixed & Improved Blender Export Script

The Blender Objective-C Export Script script has been updated to fix some problems, and to use interleaved data structures. There's a sample project, complete with a (cheap & dirty) texture, the source Blender project and the UV template for the ship.



It's intended to be used with my my OpenGL ES Xcode Template, as it uses data structures that are declared in OpenGLCommon.h.

This version also gives you the code you need to use to draw it, except for loading and binding the texture, although you can see from the sample project that doing that is easy if you use the OpenGLTexture2D class included with the project.

Note:The Texture2D class doesn't currently deal with the y-axis inversion problem, so flip your textures vertically before exporting.

A Little Ego Boost for a Friday

As I write this, the new edition of our book holds the #1 spot, and the old edition holds the #2 spot in the Mobile Devices category on Amazon:

WWDC 2009 Videos Available for Purchase

Apple is now offering the videos from WWDC 2009 for sale for none-attendees.

I've had several people ask me if they should buy these videos or ask if they "are worth it".

I've held off responding to those inquiries so far, not to be rude, but because I wanted to make sure that I was careful about my recommendation. You see, I find this a difficult question to answer for someone else. If I hadn't gone to WWDC, I would buy them without hesitation. It's hours and hours of information ranging from beginner level to advanced, with a considerable amount of information about what's been newly added and what's coming in future releases.

Your situations may not be the same as mine. As a full-time writer and programmer working only with Apple technologies, it's really important that I stay on top of things. I need to be aware of what's available as well as what's coming down the pipeline. For many independent Mac and iPhone developers, those things are equally important so they can adjust their product roadmap appropriately. For me, and I would guess for many independent developers, the answer really would be "can you afford not to". As a business expense, $300 or $500 isn't very much.

For a casual developer, however, someone with one or two iPhone applications in the store, the equation becomes more a question of can you afford them. $300 per track, or $500 for both is very reasonable for the amount of information contained in the videos and slides, but whether it's worth it for you will depend on your own financial situation and whether you need or can use that information. I don't want to give a recommendation that causes anyone to spend money they don't have or can't afford.

Are the videos great? Yes, most of them are really great. Are they fairly priced? Yes. Should you buy them?



I'm going to have to leave that last one to you, sorry.

Thursday, July 16, 2009

Beginning iPhone 3 Development is Available

Just got the word that the new edition of Beginning iPhone 3 Development is now available. This is the updated version of our first book, not the new book that covers intermediate and SDK-3 specific topics.

Wednesday, July 15, 2009

Gah! Up is Down! Right is Wrong! Make it Stop!

Today, some programmer named Zed Shaw wrote a blog post titled Is BSD The [sic] New GPL?. The crux of his article is that because a few people have, dog forbid, proselytized for the BSD license and tried to get some other projects that are currently using the restrictive GPL license to switch to the BSD license because the viral GPL license prevents code from flowing equally in both directions between the projects that, therefore, the BSD license is now just as bad as the GPL.

What... the... Fuck?

Because a few people suggested that, hey, maybe you guys would consider dropping some of those restrictions on your code so we can all, like, share equally, Zed Fucking Shaw thinks that's exactly the same as a viral license that puts restrictions, in perpetuity, on the code you write as well as on all derivative products, and any code that happened to have been stored on the same hard drive as your product for a little while1. I'd expect anti-logic like this from a marketing executive, lawyer, or clergyman, but not from a programmer. This is a pathetic excuse for logic. It's Orwellian logic. Right is wrong. Up is down. It's not missing the point, it's closing your eyes and screaming "nah-nah-nah" so you can claim you're unaware of the fucking point.

Now, I'm a big fan of openness. Almost every line of code that I've ever written that wasn't written specifically for a client or employer has been released in some form, either under a liberal license like the BSD or MIT license or simply given out as public domain code2. But I have not used and will not use the GPL. In fact, when people ask me if they can include code I've written in a GPL'd project (which they don't have to do, so I do appreciate the gesture) I always grant permission, but specifically request that they document the fact that my code is not covered by the project license.

I'm not a fan of the GPL quite simply because I don't see the GPL as "open". The GPL is not defined by what it is, it's defined by what it isn't. It's "against" proprietary closed source code. It's against corporations. It's against software as a commercial product. It's all about what it's not. It's a political movement replete with a manifesto. No joke. A fucking manifesto. The GPL is about openness in the same way that Stalin was about peace and kindness. And you know what? I don't want my code tied up in a political movement. If I want to share, I'll happily share with no expectation of a direct return. If I don't want to (or can't) share, I won't publish my code.

Sir Isaac Newton uttered a very famous line long ago in what is one of the greatest displays of modesty ever recorded. He said, "If I have seen further it is only by standing on the shoulders of giants." And that modest statement sums up the way science, and all meaningful pursuit of knowledge works. Knowledge is expanded when it is shared. When solutions to problems are shared, that frees us up to tackle the next obstacle rather than spending time solving problems that have already been solved by others. Which, if you read their propaganda, is exactly what the GNU foundation people think they believe. But anyone who has actually read their license terms knows that obviously they don't, because you can't reconcile that with the viral restrictions in their licenses. If you truly believe that knowledge is not a zero-sum game, and that sharing knowledge tends to increase the sum of societal knowledge, then you don't go putting petty restrictions on your knowledge.

Sometimes, when you fight fire with fire, all you get is a bigger fire and you certainly don't put out a fire by loudly exclaiming that water is the new fire.



Footnotes
1 - Okay, I'm kidding about the last one.
2 - Well, that's not completely true. I also don't release code that I know is bad because I don't want people copying or learning from code I know has serious problems.

New Device Rules

Jim Dovey has discovered thatthe rules surrounding device registration for ad hoc development have changed. It's not a good change for those of us who deal with multiple clients in the course of a year.

Updating Project Hint

If you update an Xcode project from SDK 2.x to SDK 3.x, and you get some really weird compile errors in UILocalizedIndexedCollation (or other UIKit classes) when Xcode processes the precompiled headers, the problem is probably that you need to change the compiler version from GCC 4.0 to GCC 4.2. The project templates were updated, so this isn't an issue with starting new projects, but when updating an older project, you have to manually change the compiler being used.

You can do that by selecting Edit Project Settings... from the Project menu, and navigating to the Build tab.

Look for the entry called C/C++ Compiler Version, and change it from GCC 4.0 to GCC 4.2

Tuesday, July 14, 2009

Detail Editor Update: To Many Relationships

Click image for larger version


As you can see above, I've got the to-many relationship editing working in my property-list driven generic detail editing pane class. Still some really rough edges, but the basic functionality now works. You can select multiple managed objects of the type used for the relationships and, as with the to-one relationship, you can add new items as well.

Monday, July 13, 2009

Generic Detail Editor Update

As part and parcel of working on the next book, I've been working on the generic detail editing pane controller, and I'm actually pretty happy with the way it's shaping up. Here's a snapshot of the sample application being written for the book that uses this new detail editing pane controller:

Click for larger version


As you can see, I've now added the ability to edit date attributes:

Click for larger version


As well as the ability to edit "to-one" relationships. For "to-one" relationships, the user is allowed to select from a list of objects from the other destination entity:

Click for larger version


And optionally can allow the user to insert new managed objects of the destination type. When the user clicks the "Add new…" row, it takes them to another detail editing page that uses another layout property list file.

The application that these screenshots come from has only one custom controller class: the application's root controller. Everything else is handled by the detail editor controller and its field editor classes based on the contents of two relatively small property list files.

I've had a number of people ask if I'm willing to release the source code before the book is available. The answer to that is yes, I fully intend to release it under a non-viral open source license, but with some caveats. I won't release it until I feel it's relatively stable. Also, because I'm under the gun and behind schedule on More iPhone 3 Development, I won't be able to write much in the way of documentation or a tutorial on the framework. I also probably won't be able to release the sample application until the book is done.

August 14 Workshop

The link I previously posted for the August 14 iPhone Boot Camp NYC workshop has changed. I apologize for the inconvenience.

The reason it has changed is because the iPhone Boot Camp is offering another class immediately prior to mine. Steve Kochran, author of Objective-C 2.0, will be holding a 3 day Objective-C workshop on August 11, 12, and 13. The two workshops have been combined into a single event on EventBright:

iPhone Class Signup

The reason that the workshops have been combined is to allow attendees to sign up for both workshops, or for either workshop individually, or for any combination of days that makes sense for the student.

Sunday, July 12, 2009

A Category on NSDate

Here is a category on NSDate that makes a few somewhat common tasks that require several lines of code and turns them into a single method all. Among these methods are one that takes a date with a datetime value and turns it into a date without time, a method that calculates a new dates that is a certain number of days after the date, and a method that calculates the difference between two dates given in days.

Nothing earth-shattering, but may save you a few lines of code here and there.

NSDate-Misc.h
#import <Foundation/Foundation.h>
@interface NSDate(Misc)
+ (NSDate *)dateWithoutTime;
- (NSDate *)dateByAddingDays:(NSInteger)numDays;
- (NSDate *)dateAsDateWithoutTime;
- (int)differenceInDaysTo:(NSDate *)toDate;
- (NSString *)formattedDateString;
- (NSString *)formattedStringUsingFormat:(NSString *)dateFormat;
@end


NSDate-Misc.m
#import "NSDate-Misc.h"

@implementation NSDate(Misc)
+ (NSDate *)dateWithoutTime
{
return [[NSDate date] dateAsDateWithoutTime];
}

-(NSDate *)dateByAddingDays:(NSInteger)numDays
{
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:numDays];

NSDate *date = [gregorian dateByAddingComponents:comps toDate:self options:0];
[comps release];
[gregorian release];
return date;
}

- (NSDate *)dateAsDateWithoutTime
{
NSString *formattedString = [self formattedDateString];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMM dd, yyyy"];
NSDate *ret = [formatter dateFromString:formattedString];
[formatter release];
return ret;
}

- (int)differenceInDaysTo:(NSDate *)toDate
{
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *components = [gregorian components:NSDayCalendarUnit
fromDate:self
toDate:toDate
options:0
]
;
NSInteger days = [components day];
[gregorian release];
return days;
}

- (NSString *)formattedDateString
{
return [self formattedStringUsingFormat:@"MMM dd, yyyy"];
}

- (NSString *)formattedStringUsingFormat:(NSString *)dateFormat
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:dateFormat];
NSString *ret = [formatter stringFromDate:self];
[formatter release];
return ret;
}

@end

Friday, July 10, 2009

Core Data Default Dates in Data Model

I'm leaving this blog entry, but do not use this tip - there is a flaw in it

When creating a managed object model using Xcode's Data Model Editor, I knew that there was a way to specify a default value for a date attribute that would cause it to default to the current date and time. It's one of those things I need to do about twice a year and can never, ever remember how it's done. Apple's documentation didn't yield an answer (it might be in there, but it's not easy to find). Yes, you can create a custom subclass of NSManagedObject and set the value in awakeFromInsert:, but for those situations where you don't want to subclass, or don't feel like it, I knew there was a way and it was frustrating me that I couldn't remember it or find it.

Thanks to Twitter, I got the answer, and it's a cooler answer than I remembered. The Default field for date attributes will interpret natural language strings put in quotes. It appears to be that anything that NSDate's natural language parser can handle, the date attribute's default field can handle. "Tomorrow", "Today", "Now", "Yesteday at Breakfast".

WHOAH: After a user comment alerted me to this, I tested it out and sure enough, the natural language string entered into the default field is actually determined at compile time, not at runtime, so 'today' will always result in the same date. Do not use this technique!

via Shane Crawford

A Kick-Ass Objective-C Programmer is a Kick-Ass C Programmer

A lot of people who have come to Objective-C from languages like C# and Java don't fully appreciate the fact that Objective-C is just a thin layer on top of C. Everything that you can do in C, you can do in Objective-C - structs, unions, typedefs, functions… it's all there. So, if you want to be a truly kick-ass Objective-C programmer, you really, really need to be a great C programmer as well.

If you didn't spend some quality time with C as your primary language (as most of my generation of programmers did), you might want to consider boning up on a little old-school procedural programming.

You know who is a kick-ass C and Objective-C programmer? Mike Ash. Today, and for the previous two Fridays, Mike has been covering one of the lesser understood aspects of the C language: type qualifiers. I seriously recommend reading these (and for that matter, every one of Mike's Friday Q&A blog entries):

Type Qualifiers, Part 1
Type Qualifiers, Part 2
Type Qualifiers, Part 3

It's a great explanation of something that's not easy to explain, so unless you're a guru-level C coder, go read it them.

 
Design by Wordpress Theme | Bloggerized by Free Blogger Templates | coupon codes