Senin, 20 Juli 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.

Minggu, 19 Juli 2009

Preview: Gangstar- West Coast Hustle

Gameloft recently announced that they are working on producing a full GTA-like game for the iPhone and iPod Touch called Gangstar: West Coast Hustle.
The game is due to be released by the end of summer for an unannounced price.



Some info about the upcoming title:
  • Take on L.A Gang life in that takes you to more unique environments than ever before
  • The first iPhone crime game with full 3-D graphics for an entire city
  • Hit the streets your own way. Drive for miles non-stop completing missions in your own time or just create havoc on the streets
  • Get rich, or die trying! Steal, shoot, drive, fight, walk your way to a life of riches by helping out relatives and gangs. If the police don't stop you first
  • Controls designed perfectly for the iPhone. Drive using the accelerometer and shooting is made easy with automatic aiming
  • Be your own inner Gangster by listening to any music station you want, or even music from your iPod
This game seems like one not to miss out on. Just to keep you hungry for more here are a few screenshots from what looks like a super impressive game.





Jumat, 17 Juli 2009

Defender Chronicles


iTunes Link

Defender Chronicles is a tower defense game by Chillingo. $0.99

[A Modified post from TheAppEra]

Chillingo sneaks in a great tower defense app, especially for those who love the Role playing ingredients.

Combining the addictive and easy-to-learn gameplay of a tower defense game with story RPG elements, and immersive game world, Defender Chronicles delivers a brand new gaming experience like nothing you have played before. Returning to the glory days of epic battles, desperate princesses, artifacts hunting, and marvelous fantasy beasts. Travel the path of a warlord as you lead an army through the invasion of the Orc Hordes and the rising Undead.

I have been a big fan of Tower Defense games on the App Store, with this being the perfect platform for games like this. Before the iPhone the only tower defense game I played was Bloons Tower Defense. Defender Chronicles is totally different to any other game of its genre, straying away from both the open field of Fieldrunners and flat field of The Creeps and Star Defense. Instead Defender Chronicles takes the game vertically, with Orcs going from the bottom up or vice versa. It is a great concept pulled off beautifully

First of all, the Role Playing elements are evident just by the artwork alone. Everything form the campaign to the locations, the enemies and the weaponry screams RPG. There’s even a story being told (yes I admit I skipped it) in spoken word and in text as it’s being read to you. Hey the theme and presentation fits perfectly with the gameplay.

I have been playing this game from the very first build of the game and I am happy to say that is progressed extremely well to put out the final product that we see today. The graphics has progressed immensely during its production time and the many creatures that are featured in the game is quite superb. The number of monsters from what seems like the Lord of the Rings era is superb to say the least. There are a large range of maps with different backgrounds everytime.

The one small letdown from the graphics is the fighting animation. When your soldiers come up against a monster they take it in turns hitting each other until one dies. The animation in the fighting is each character taking a swing at the other, looking like nothing at all happened when they are hit. I think it could be a bit more intense then what it currently is.

The sound tends to get clustered during the game. For example, when you upgrade a warrior in the middle of a wave, the clashing of swords, enemy battle cry, or for those soldiers awaiting duties can NOT be heard. It hits a certain level, and it starts to either cut out or overlap creating excess noise. While it is a part of the game, it would be a nice to turn off the sound effects altogether. The background music is overpowering the sound effects. I would like improvements to be made to this.

The object of the game is to protect your gate while wave after wave of enemies come through the path in single file fashion. So as they trek down the path to the gate your Hero is protecting, you are supposed to set up certain checkpoints as such to slow down and kill off the enemies from crossing the gate. Once a certain number of Orcs or whatever crossing the gate, you succumb to defeat.

As the Hero, you set up the checkpoints with either warriors, archers, or halflings. As you gain gold coins, you have the option of upgrading their attack to a higher level in order to take on the tougher foes. Warriors (they look like medieval knights) change over to Berserkers with axes. Archers upgrade to Rangers. I’m not sure about the halfings and what they upgrade to since the Marshwood level is needed to be beaten to get them. And I haven't been able to do that yet. Some of the attacks don’t work on certain foes, so a mixture of arrows and swords need to be strategically placed and in time before a massive wave comes through and runs over your entire army.

There are 4 levels of play, starting in casual mode and working through veteran, heroic and master, your Hero levels up with experience. Per victory at a specific location, stars are rewarded to depict your victory’s level of difficulty. Harder levels give you less lives and the enemies are also harder to defeat. Beating harder levels will give you more EXP points as such to upgrade certain stats in the shop.

With each win or battle experience, you gain tokens to purchase weaponry to increase your Hero’s attack or defense in the Trade Shop. Those are hard earned by the way and every bit helps however small the reward is. Also you have the right or temptation to buy other soundtracks with those some tokens. Those are found in the Great Library. While I don’t understand why you would buy a soundtrack, the option is there if you decide on music over armor and a new sword.

In case you breeze through campaign mode, you have the option of a random freestyle game, extended, classic or classic extended. It’s good to have these choices if it’s too easy for you in the defaults. Customization extends the life of this game by leaps and bounds. Let’s not forget about the Fast Forward option either. When one Orc is taking its time strolling through the mountainside, hit the fast forward button to speed things up. Or for those who can handle it, leave fast forward on the whole time.

Defender Chronicles has been made to keep you playing the game long after most other games of the same genre, just because of the RPG style that requires you to play it levels multiple times. The game is currently on sale for $0.99 and it an absolute gem at that price. I would rate this game in the top 3 tower defense games along with Fieldrunners and Star Defense. For a first time developer who has had great help from publisher Chillingo to get this game noticed it is a top effort. Any RPG or tower defense fans will seriously enjoy this game!

Gameplay- 9.5/10
Graphics- 8/10
Sound- 7/10
Overall- 8.5/10

I would recommend this game if you enjoyed- Star Defense

Tell me what you think about this review at Twitter- http://www.twitter.com/iPhone_Reviews next up is Gangster Preview!

Thanks- iPhone_Reviews

New York Nights- Success in the City



iTunes Link

New York Nights: Success in the City is a sim game by Gameloft. $0.99

[A Modified post from TheAppEra]

NY Nights was released before The Sims 3 and realistically had a small time space to crack the top 50 before The Sims 3 came along and made everyone who hadn't bought this forget about it. This sadly never happened and even with a price drop to $0.99 the game hasn't seen its own 'Success in the City'.

This game however is far from deserving its bad rap and sales. The game is super addictive, providing many hours of entertainment that is a lot different to The Sims 3. NY Nights strays away from free playing nature of The Sims 3 and provides a more direct storyline that you must follow to continue unlocking new areas and people. The graphics are more 2D and remind me of the popular online PC game Habbo Hotel.

As I just said above the graphics are 2D and very similar to Habbo Hotel. The graphics are perfect for this type of game, and there is actually alot of detail in the game. There are about seven locations to travel around in New York with multiple buildings and houses available to look inside around the city. They are bright and look fantastic, giving the real feeling that certain areas of New York provide.

The animation in this game appears everywhere, as people are dancing and talking and trying to stand up like a drunk person without you talking to them. There are people moving in all directions in all areas, again giving the feeling of being in a busy part of New York.

New York Nights is all about point and clicking and telling your New Yorker what to do. It is far from the engaging parts of The Sims 3, but uses the same type of set-up as what is in the majority of The Sims series. What sets this game apart from others is the absurd options that you can get at times. You get a chuckle when you try to make friends with a person on the side of the street but one of the options is to make the person drunk.

These controls aren't the best for all situations however. When in certain areas like on the dance floor it is incredibly clustered and trying to go to a certain place or do an action is more of a hit or miss in whether you get the option to pop up or not. Generally though this process works extremely well and is easy to pick up and play for the first time without the need to read up on how to use the instructions.

Take your New Yorker to the streets as they follow a life of either friendship or fame. As you venture through six districts of New York as well as various buildings you will find your character and your pathway. New York Nights gives you 40 game days to become as successful as you wish to be, but the main part of the game will take you considerably less.

The game follows a kind of career mode with 7 chapters to complete. Whether it is from paying the rent, getting your first job at the local nightclub or meeting the world famous Starlet, it will take you on an action packed journey with love, laughs and tears. There aren't really many choices you get to make in the way the story works out, with two endings that are irrelevant to how the game pans out. Still the first time you play this game and reach one ending I was convinced to complete the game once again to see what happens if I chose the other option.

Like in the Sims you have to worry about how your character is feeling in all different ways. You have many stats such as your body, your social state and how bad you need to go to the toilet. Maintaining these is pretty easy but how well you upgrade your stats will determine how people think of you in the town. The game is all about people a fun simulation game that is meant to let real New Yorkers relate to the feelings experienced in the town.

What I didn't expect in a game like this was quite a bit of comedy. Some of the quotes and sayings that come up in the chat between various characters is hilarious and would make the characters in Zenonia proud. When asking some people about their favorite game they confidently say that Asphalt 4 Elite Racing is absolute amazing. Another time I managed to talk a girl into saying that she starting hitting on another girl only to find out that it was a dude with a mullet.

The game actually has a decent amount of fun content to play around with. The career mode will take about 2-3 hours to complete, but what lets this game down is that once the career part has finished and you are left to explore New York there is absolutely nothing to do. Sadly the incentive to continue playing went out the window and I went onto other games like Asphalt 4 Elite Racing which has some of the coolest cars around!

For $1 New York Nights provides a great casual sim game that will guarantee to give you a good 4-5 hours of entertainment. The game is no where near the quality and class that The Sims 3 will provide you, but if you aren't looking for the A+++ experience then this will do you just fine. Of course the game is from Gameloft so quality is a given with them.

Great graphics, a straightforward storyline but with a lot of laughs is a basic wrap-up of what you will find in the center of New York. This is easily one of the best $0.99 games. This is one that you seriously need to consider picking up.

Gameplay- 8.5/10
Graphics- 9/10
Sound- 6.5/10
Overall- 8/10

I would recommend this game if you enjoyed- The Sims 3

Tell me what you think about this review at Twitter- http://www.twitter.com/iPhone_Reviews next up is Defender Chronicles

Thanks- iPhone_Reviews

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Lady Gaga, Salman Khan