2011年12月27日星期二

Get List of Installed International Keyboards

Get List of Installed International Keyboards:
The NSUserDefaults object is typically used to save/restore your application related preferences, configuration data, etc – see Write and Read User Preferences for more information. In addition to application specifics, there is a system wide default list that is available to all applications, accessible using the class method standardUserDefaults in the NSUserDefaults object.
To get a list of the system wide settings:
NSDictionary* defaults = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation];
NSLog(@"Defaults: %@", defaults);
A partial list of the output on my device follows:
Defaults: {
   AppleICUForce24HourTime = 0;
   AppleITunesStoreItemKinds =     (
       wemix,
       podcast,
       ...
   );
   AppleKeyboards =     (
       "en_US@hw=US;sw=QWERTY",
       "zh_Hant-HWR@sw=HWR",
       "emoji@sw=Emoji"
   );
   AppleKeyboardsExpanded = 1;
   AppleLanguages =     (
       en,
       "zh-Hant",
       fr,
       de,
 ...
}
As you can tell, the defaults returned above are contained within a dictionary object. The list of keyboards in the dictionary is stored as an NSArray object. To retrieve the array, simply request the object for the key “AppleKeyboards”
NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleKeyboards"];
NSLog(@"Keyboards: %@", array);
The output of all the installed international keyboards looks as follows:
Keyboards: (
   "en_US@hw=US;sw=QWERTY",
   "zh_Hant-HWR@sw=HWR",
   "emoji@sw=Emoji"
)

2011年12月26日星期一

Migrating your code to Objective-C ARC

Migrating your code to Objective-C ARC:
Recently, Apple introduced several new developer stuff including Xcode 4, ARC, LLVM Compiler 3.0 and iOS 5. From some of the questions on Stack overflow, I could understand that, most of the ARC related confusions arise due to the fact that, developers don’t know if “ABC” is a feature/restriction of LLVM 3.0 or iOS 5 or ARC.

Retain cycles, auto-release pools, @autorelease blocks, oh man! So many new things? What am I going to do? You are right. ARC, or Objective-C Automatic Reference Counting is almost as magical as the iPad. No really!

In this post, I’ve made an attempt to demystify the air around this. Before starting, I’ll have to warn you that, this is a fairly long post. If you are too bored, Instapaper this article and read it later. But, hopefully, at the end of this, I believe, you will have a better understanding on how ARC works and be able to work around the innumerable errors it spits out when you convert your project.

Having said that, let’s get started.

What is ARC


ARC is a feature of the new LLVM 3.0 compiler that helps you to write code without worrying much about memory management. Memory management can be broadly classified into two, garbage collected and reference counted models. Before going to the details, let’s briefly discuss these two models and understand why ARC is even needed.

Problems with the current model.


The current memory model we use in Objective-C is manual reference counting on iOS and Garbage collection on Mac.

There are certain problems with both these memory models which probably was the reason why ARC was developed.

Garbage collection

Garbage collection is a higher level language feature probably introduced in Java (or technically, Java Virtual Machine) and implemented in a variety of other programming platforms including Microsoft’s Common Language Runtime. While Garbage collection worked well for higher level languages, Objective-C, which is still C under the hood, didn’t really fly high. Pointers (or rather references) in other languages like Java were actually objects that managed retain count and automatically releases itself when the count reaches zero. One of the design goals of C was to be optimized for performance and not “easy of use”. While pointer objects (read smart pointers) are great object oriented abstractions, they have an adverse effect on the performance of the code and since Objective-C was intended primarily for native programming where developers are used to use pointers, pointers within a structure, pointer to a pointer (for dereferencing a out parameter), it was just too difficult to introduce something like a smart pointer that would require a lot of mindset change from the developers who prefer a deterministic memory management model (Reference counting) over a non-deterministic memory management model (Garbage collection). Nevertheless, GC (Generational GC) was introduced in Objective-C 2.0 for Mac. While Generational GC doesn’t suffer from “Stop the world” issues like the mark and sweep alogrithm, they don’t collect every released variable and an occasional mark and sweep collection is still needed.

Reference Counting

The memory management model used in iOS is called as reference counting model, or more precisely, manual reference counting.

In manual reference counting model, you as a developer, have to deallocate every object you allocated. When you don’t do this, you either leak memory or over release it, causing a crash. While that counting sounds easy, Most of the memory leaks happen when you transfer ownership of objects across scope boundaries. That’s a creator method that allocates an object for you and expects the caller to deallocate it. To circumvent this problem, Objective-C introduced a concept called autorelease. auto-released variables are added to the auto-release pool and are released at the end of the runloop. While this sounds too good, auto-release pools do incur an additional overhead.

For example, comparing the two code blocks,


{
NSDictionary *dict = [[NSDictionary alloc] init];
// do something with the dictionary here
// I'm done with the dictionary, I don't need it anymore
[dict release];
// more code
}


and


{
NSDictionary *dict = [NSDictionary dictionary]; // auto-released object
// do something with the dictionary here
// I'm done with the dictionary, I don't need it anymore

// more code
}


the first block is an example of optimized use of memory where as the second depends on auto-release pools. While this block of code doesn’t really incur significant memory overhead, code like these slowly adds together and makes your reference counted model heavily dependent on auto-release pools. That is, objects that you know could be deallocated, will still linger around in the auto-release pool for a little longer.

Automatic Reference Counting

Say hello to ARC. ARC is a compiler feature that auto inserts retain and release for you. So in the first code block of the above example, you no longer have to write the release method and ARC auto-inserts for you before compilation.


{
NSDictionary *dict = [[NSDictionary alloc] init];
// do something with the dictionary here
// I'm done with the dictionary, I don't need it anymore
[dict release]; // ARC inserted
// more code
}


When you create an autoreleased object, like in the second block of code, ARC compiler is clever enough not to add a release call. Sound great, so how should I go about doing this ARC thing? Just delete all release/retain codes and pray? Unfortunately, it isn’t that easy. ARC is not just some auto insert or macro expander kind of tool. It forces you to think in terms of object graphs instead of memory allocation, retain or release. Let’s delve a little deeper into ARC.

Compiler level feature


ARC is a compiler level feature. I repeat. ARC IS A COMPILER LEVEL FEATURE. This means, when you use ARC, you don’t have to worry about upgrading your deployment target and so on. However, only the latest LLVM 3.0 compiler supports ARC. If you are still stuck with GCC, you are out of luck. (Meh!) Some more points that you should know about ARC are,

  • ARC is backward compatible with libraries and framework compiled with under non-ARC.
  • ARC can be used within your project on a file-by-file basis. So you can mix and match ARC code with non-ARC code.
  • You can also integrate ARC compiled libraries into your project that doesn’t use ARC and vice-versa.
  • You use a compiler switch to turn ARC on and off.
  • (The keyword here is compiler switch)
  • You can also set the complete target to build with ARC by default (and use non-ARC compiler only when instructed so.) This is shown in the illustration below.
  • ARC  Xcode

The two main compiler switches that you would often use are when you build your application with a third party library that is not ARC compliant and vice versa, are

  • -fno-objc-arc
  • -fobjc-arc

-f is the switch and no-objc-arc and objc-arc are the options that you are turning on. As evident from the names, the first one turns off ARC and the second turns on.

For example, if your application is ARC enabled but a third party library is not, you use the first switch -fno-objc-arc to exclude the third party library. Conversely, if your application is not yet ARC enabled (gasp!) but the third party library you are integrating is, you use the second switch -fobjc-arc You add these flags to the project from the Build phases tab as shown below.Xcode 2 1

Also a run time feature


Wait! You just told me (and repeated) that ARC is a compiler level feature? Now what? Sorry, I hear you, but, unfortunately, things aren’t that easy and it doesn’t just stop here. ARC also backs up on a runtime feature called zero-ing weak references. Oh, damn, another keyword! I should have introduced this before. But that’s ok. We will revisit about the run-time dependency of ARC, a little later in this post.

ARC Ownership qualifiers


As I showed you earlier, ARC automatically inserts releases and retains in your code in a pre-compilation step. But for ARC to know when to release your objects and when to retain them, you need to somehow tell the life of your variables. You use ownership qualifiers for that. A strong understanding of ownerships is vital to understand and use ARC properly. Once you understand this concept, you will be thinking in terms of object graphs instead of retain/release. Secondly, when you use ARC, all variables local or ivars are initialized to nil automatically for you. This means, there is little chance of having a dangling reference in your application.

  • __strong
  • __weak
  • __unsafe_unretained
  • __autoreleasing

The first qualifier, __strong, is the default and you might not even be using this explicitly. It is use to tell the ARC compiler that, the declared variable “owns” the reference. The opposite of this is __weak, which tells the ARC compiler that the declared variable doesn’t own the reference.

The __weak is synonymous to the “assign” modifier. You normally use assign modifier for IBOutlets and delegates. Under ARC, this is replaced with __weak. However, there is a caveat. __weak requires you to deploy the app on a runtime that supports zero-ing weak references. This includes, iOS 5 and Lion. Snow Leopard and older operating systems or iOS 4 and older operating systems don’t support zero-ing weak references. This obviously means you cannot use __weak ownership modifiers if you plan to deploy to older operating systems. Fret not. ARC includes another ownership qualifier, __unsafe_unretained that is synonymous to __weak, except that when the pointer is de-referenced, it is not set to nil, but remains dangling. A while ago, I told something about zero-ing weak references? When the runtime supports zero-ing weak references, your __weak variables are automatically set to nil when they are released. This is the only feature that requires a higher deployment target (iOS 5/Lion). Otherwise, you are good to deploy on iOS 4/Snow Leopard.

A couple other important things to know about __weak vs __unsafe_unretained is that, the compiler doesn’t allow you to use __weak when your deployment target is set to a operating system that doesn’t support zero-ing weak references. The Convert to Objective-C ARC wizard uses __weak only when your deployment target supports zero-ing weak references. So if your deployment target is iOS 4, the Objective-C convert ion wizard will replace assign modifiers with __unsafe_unretained instead of __weak.

The last ownership qualifier, __auto_releasing is used mostly when passing a reference to a function for writing out. You would use this in places where you normally use pointer indirection like returning a NSError object via an out parameter.

Properties in your header file can also have the above ownership qualifiers except the __auto_releasing. When applied to properties, ARC automatically generates the correct code in dealloc to release them when the object dies.

Lastly, and more importantly, all of ARC managed objects are initialized to nil when they are created. So, again, no more dangling pointers because you forgot a initialize statement. However, do note that this initialization doesn’t initialize primitive data types. So a declaration like,


int a;


might contain a garbage value for a.

Whew! That’s pretty taxing. Take a break. We just started.

ARC knows more Objective-C than you


ARC also taps into a the Objective-C language naming conventions and infers the ownership of the returned object.

In Objective-C, a method that stats with any one of the following prefix,

  • init,
  • alloc,
  • copy,
  • mutableCopy and
  • new

are considered to be transferring ownership of the returned object to the caller.

This means, in your application, when you create a method, ARC automatically infers whether to return a autoreleased object or a +1 retained object from your method name. In fact, in most cases, instead of returning auto-release objects, ARC just inserts a manual release in the calling code, automatically for you. However, there is a small caveat. Let’s assume that you have a method that starts with “copy”, as in


-(NSString*) copyRightString;


ARC assumes that it would transfer the ownership of the returned string to the caller and inserts a release automatically. Everything works well, if both the called method and the calling method are compiled using ARC.

But if your “copyRightString” method is in a third party library that isn’t compiled with ARC, you will over-release the returned string. This is because, on the calling code, ARC compiler inserts a release to balance out the retain count bumped up by the “copy” method. Conversely, if the third party library is compiled with ARC and your method isn’t, you will have a memory leak. You can however override this behavior by adding one of the following attribute to your methods.

  • NS_RETURNS_NON_RETAINED
  • NS_RETURNS_RETAINED

So your method will now look like this.


-(NSString*) copyRightString NS_RETURNS_NON_RETAINED;


You can also rename the method name to copyrightString (note the case) or getCopyRightString instead of adding an attribute. However, I wouldn’t recommend the former method as it breaks the cocoa naming conventions (prefixing a method with “get” or “set” is Java-ish)

You will see methods having the NS_RETURNS_* prefixes throughout the header files in Apple’s own UIKit.framework or the foundation classes. Now that you know what happens behind the scenes and how compiler treats these decorations, you can solve crazy memory issues, like a crash when you call a copyRightString in your method in a third party library.

With that, let’s get ready for climbing the next peak.

Toll-free bridging


ARC doesn’t manage Core Foundation objects. They say, there is no free lunch. ARC, takes it one step further. There is no free-casting between Core Foundation objects and equivalent Objective-C objects (NS* objects). Yes, that’s right. You cannot cast a Core Foundation object to an equivalent Objective-C object (NS* object) without telling ARC how to manage ownerships.

Let’s now see how to specify ownership transfers when you cast a Core Foundation object.

The following ownership transfer modifiers should be provided when you cast a Objective-C object to a Core Foundation object.

  • __bridge
  • __bridge_retained
  • __bridge_transfer

When you migrate a project to ARC, you would have seen error messages like the one below.

Toll free bridging
ARC Error because of a missing bridge attribute in a Toll-free bridging code

You might also have proceeded by accepting the suggestions provided by the LLVM compiler. But now, let’s dig deeper and understand the “why” behind it.

The modifier, __bridge tells the ARC compiler that, it’s a plain simple, bridging cast. That means, you ask the ARC compiler to do nothing extra when the transfer is made. You might think, if that is the case, Apple could have made this the default choice. But it was not made probably because, it’s to preposterous to make such an assumption. Making such a bold assumption means, you would easily leak memory as there isn’t a easier way to tell when you are actually releasing a Core Foundation object unlike a Objective-C object.

The second modifier, __bridge_retained is used to tell the ARC compiler that the Objective-C object should be transferred to Core Foundation by bumping the retain count by 1 and it should be treated as if it is a newly created object (as opposed to a auto-released object). You use this modifier if the method was probably named like a creation method (starting with init, copy, mutableCopy etc.,) or if you are going to release the Objective-C object inside of Core Foundation using methods like CFRelease.

The last modifier, __bridge_transfer is used to tell the ARC compiler that the Core Foundation object is to be transferred to ARC with a retain count of 1. This is used if you created a Core Foundation object using one of the CF***Create methods and want the ARC compiler to handle the memory management for you. That’s you are transferring a Core Foundation object to ARC with a retain count of 1.

As a side note on this, avoid using __bridge_retained and __bridge_transfer to trick the compiler to add retain and releases for you. Use it to improve your code readability and minimizing the number of manual memory management calls. (Move on if you don’t understand this line. You will start understanding this automatically when you start using this in your own code)

How does ARC work internally?


ARC ain’t magic, if you know how it works. But a little knowledge is a dangerous thing. Knowing how the ARC compiler works will help you more in understanding the error messages and compiler warnings spat out by it.

The ARC compiler has two main parts, a front end compiler and an optimizer.

ARC front end


The ARC front end compiler checks for every “owned” Objective-C object and inserts release appropriately. By owned object, I mean, an object whose ownership qualifier has been set. For example, if the “owned” object is a local variable, ARC front end compiler inserts a release at the end of the scope. This is because, by default all local variables are “strong” ly owned. If the object is a instance variable, the ARC front end compiler inserts a release statement in the dealloc method, if the ownership type is strong. For unsafe_unretained or weak ownership ARC doesn’t do anything. It also takes care of calling the [super dealloc] for you and intact ARC compiler doesn’t allow you to explicitly call dealloc.

The ARC front end compiler also takes care of generating errors when it encounters a variable (local or instance) whose ownership qualifier is not set or when you explicitly calling dealloc.

ARC optimizer


The function of the ARC optimizer is to optimize the retain and release statements by removing them if they are inserted multiple times by the ARC front end compiler. It is this optimizer that ensures that performance is not affected by calling retain and release multiple times.

The actual Migration using Xcode 4.2


Xcode 4.2 has a wizard to automatically migrate your code for use with the ARC compiler. This means, the wizard rewrites some of your code, removes calls to retain/release and removes dealloc methods and calls to [super dealloc] for you.

The first step is to open your project, select Edit -> Refactor -> Convert to Objective-C ARC from the menu.

Refactor option
Migrating to Objective-C ARC using Xcode 4.2

When you select this option, you will be asked to select a target. If you have only one target, it’s fine. If you have multiple targets in your application, you have to perform the ARC migration on every target. After you select a target, the wizard by default selects all source code files that belong to that project for ARC migration. If you are using third party libraries that are not yet ARC ready, you can uncheck those files in this step. This is illustrated in the screenshot below.

Cannot convert
Selecting your files for ARC exclusion

In the above project, since I know that ASIHttpRequest is not yet ARC compatible, I’m selecting them and command-clicking them to show the option to uncheck all of them. When you do this, the wizard automatically adds a -fno-objc-arc compiler flag for all these files.

The next step is to start the pre-checking process. The pre-checking process compiles the project and analyzes for potential problems before performing the actual migration. You might almost and always get a error message like this.

Cannot convert
The dreaded error message!

Of course, 58 errors in this screenshot is actually quite low. You should expect anywhere in the range of 300+ for a mid sized project. But fret not, they aren’t complicated at all to fix.

Common ARC migration errors


The number of errors that might prevent you from converting your project to ARC is usually high if your code is “old” or if it doesn’t adhere to Objective-C design patterns. For example, accessing a iVar. While it’s technically ok, you should almost and always use properties to access them outside of init and dealloc methods. If you have been using properties, ARC migration would be painless. If you were old skool, you have to feel the pain now. In this last section, I’ll show you the most commonly occurring errors when you migrate your project.

Cast of Objective-C pointer to C Pointer type


This error is generated because ARC doesn’t do toll-free bridging for you. As I explained before in the section, Toll-free bridging, requires the developer to explicitly specify ownership transfer qualifiers.

Use the various ownership transfer qualifiers I showed you before to fix this problem.

performSelector may cause a leak because its selector is unknown


We now know that Objective-C ARC compiler knows more Objective-C than you. This error message is because of that. The ARC compiler tries to identify the method family and determine whether to add a retain or release to the returned value from the caller code. This means, if your method starts with init, alloc, copy, mutableCopy or new, the ARC compiler will add a release to the calling code after the variable scope ends. Since are using a selector to call a method dynamically at runtime, ARC doesn’t really know if the method called returns a +1 retained object or a auto-released object. As such, ARC cannot reliably insert a retain or release to the returned object after its scope ends. This warning is shown to warn you of potential memory leaks.

If you are sure that your code works fine without memory leaks, you can ignore this warning. To suppress this warning, you can turn off the compiler flag -Warc-performSelector-leaks warning on a line by line basis like this.


#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[self performSelector:self.mySel];
#pragma clang diagnostic pop


Unfortunately, you cannot annotate a dynamic selector using __attribute__ ((objc_method_family(*))).

Receiver type “*” doesn’t declare the method with selector “*”


ARC mandates that every method you call should be declared properly. With GCC, this was a warning. But LLVM makes this step mandatory since ARC needs to accurately identify and that is why you see an error like this.

Undeclared Selectors
Error that you see when you don't declare a receiver type

This error is also because of the fact that ARC needs to identify the method family to determine if it has to add a retain or release to the returned object. For example, in the above code, the method, returnMyGreatObject might return a NS_RETURNS_RETAINED. In this case, the ARC compiler has to insert a release after the returned object goes out of scope. The ARC compiler can know this only when you declare it formally. This is why, under ARC method declarations are mandatory. If you have been declaring methods formally under GCC, even when the compiler didn’t enforce (so that the code was aesthetically beautiful) you wouldn’t see this error at all. As I said before, the number of ARC migration errors is directly proportional to the quality of code you write. Fixing this error is fairly simple and all you have to do is to declare every method formally in the header file or on a private category extension.

Common workarounds that you use in ARC on code that otherwise looks normal


In some cases, while using ARC, you might end up writing code that looks as if it’s written to “please” the ARC compiler rather than writing natural code. Unfortunately, nothing can be done to this and we all have to live with this. The next two sections explain when you might need to write unnecessary code like this to please the compiler.

Capturing “*” strongly is likely to lead to a retain cycle


Capture
ARC and retain cycles

The last category of warning message is shown when a retain cycle is detected in your code. An example is shown below.

This code was probably leaking the request object before ARC and increasing your memory footprint. But, thanks to ARC. You now know that code like these cause retain cycles that cannot be released automatically. Circumventing a retain cycle issue almost and always ends up breaking the cycle with a weak reference.

Fixing this error is fairly simple and in this case, you can get a weak reference to the request object and copy it to the block. Within the block, convert it again to a strong reference. This is illustrated below.

Capture fixed
Workaround for ARC and retain cycle issue

In the above code block, you can also replace references to __unsafe_unretained with __weak if you are deploying to a runtime that supports zero-ing weak references.

Avoiding retain cycles using __block


Sometimes, you need an object to live till as long as the completion handler on it can live. For example, a Block based UIAlertView can call a completion handler after the user presses a button on the UIAlertView.

For example,


UIAlertView *alertView = [UIAlertView alertViewWithTitle:@"Test" buttons:[NSArray arrayWithObjects:@"Ok", @"Cancel", nil] completionHandler:^(int tappedButtonIndex)  {

// do something based on the button tapped on alertView
}];
[alertView show];


In the above case, the alertView gets deallocated by ARC as soon as it’s shown and the call to completionHandler never gets executed (or even crashes).

To prevent this, you can use the __block decoration on UIAlertView declaration and copy it inside the block like


__block UIAlertView *alertView = [UIAlertView alertViewWithTitle:@"Test" buttons:[NSArray arrayWithObjects:@"Ok", @"Cancel", nil] completionHandler:^(int tappedButtonIndex)  {

// do something based on the button tapped on alertView
alertView = nil;
}];
[alertView show];


ARC takes care of releasing it when you nil it inside the completionHandler. You will find this pattern used a lot when you work with completionHandlers in TwTweetComposeViewController or even UIViewController presentViewController:animated:completion: methods.

That last question


When should you migrate?


NOW

The performance benefits you get by using ARC is remarkable. Apple claims that the @autoreleasepool is over 6 times faster than NSAutoReleasePool objects used in your non-ARC code. This is because, @autoreleasepools don’t allocate objects and all it does is must bump up the pointer retain counts. Similarly, NSObjects’ retain and release are optimized that you can expect a performance boost of anywhere around 2.5x. The third important performance benefit you will see is in methods that return autoreleased object. Under ARC, this variable is no longer transferred using the auto-release pool and what instead happens is a ownership transfer. Again this is upto 20x faster.

Hence, don’t wait till your dependent third party frameworks are migrated to ARC. You can always exclude them and go ahead and convert your code to ARC now.

Where to go from here?


  • WWDC 2011 – Session 322 Introduction to Automatic Reference Counting
  • WWDC 2011 – Session 322 Objective-C Advancements in depth
  • Stop: You are warned. This link is only for hard code geeks. http://clang.llvm.org/docs/AutomaticReferenceCounting.html
  • WWDC 2011 – Session 308 – Blocks and Grand Central Dispatch in Practice

One last word, treat this post as a living document. I’ll be updating the last few sections on new workarounds as and when I find a fix for them.

–

Mugunth

2011年12月22日星期四

Build a Caterpillar Game with Cocos2D: Movement and Missiles

Build a Caterpillar Game with Cocos2D: Movement and Missiles:
This entry is part 5 of 5 in the series Build a Caterpillar Game with Cocos2D
This is the fifth installment of our Cocos2D tutorial series on cloning Centipede for iOS. Make sure you have completed the previous parts before beginning.





Last Time…


In the last tutorial, we discussed the AI of the caterpillar. You learned how to move the caterpillar through the sprout field as well as the bounds of the level.

In today’s tutorial, we will be jumping all over the place as we discuss the player movement/interaction and firing missiles.



Step 1: Controlling The Player


Controlling the player is actually quite simple. The first thing we need to do is tell our game layer to swallow touches in order to interact with it. Add the following code to your init method in GameLayer.m:

[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];

As you saw in the first tutorial, this line of code will simply allow GameLayer to be a touch delegate allowing it to receive notifications of touches. Now, there are two methods that we need to implement. Add the following methods to GameLayer.m

// 1
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
return YES;
}

// 2
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
// 3
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];

CGPoint oldTouchLocation = [touch previousLocationInView:touch.view];
oldTouchLocation = [[CCDirector sharedDirector] convertToGL:oldTouchLocation];
oldTouchLocation = [self convertToNodeSpace:oldTouchLocation];

// 4
int xChange = touchLocation.x - oldTouchLocation.x;
int yChange = touchLocation.y - oldTouchLocation.y;

int newX = self.player.position.x + xChange;
int newY = self.player.position.y + yChange;

// 5
if(newX < kGameAreaStartX + kGameAreaWidth - kGridCellSize &&
newX > kGameAreaStartX &&
newY > kGameAreaStartY + kGridCellSize / 2 &&
newY < kGameAreaStartY + (kGridCellSize * 3)) {

__block BOOL collide = NO;
CGPoint oldPosition = self.player.position;
// 6
self.player.position = ccp(newX,newY);

// 7
[self.sprouts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Sprout *sprout = (Sprout *)obj;
CGRect sproutRect = [sprout getBounds];
CGRect playerRect = [self.player getBounds];

if(CGRectIntersectsRect(sproutRect, playerRect)) {
collide = YES;
*stop = YES;
}

}];

// 8
if(collide) {
self.player.position = oldPosition;
}
}
}

  1. We first need to implement the ccTouchesBegan method to let the caller know that we are responding to touches. If you omit this, your game will crash.
  2. Next, is the ccTouchesMoved method which gets called when the player drags their finger on the device.
  3. Get a reference to the coordinates of the current touch location and the coordinates of the previous touch location.
  4. Get the change from the old location to the new one. We will use this change to determine how far the player should move.
  5. Here we have a series of checks to ensure that the player stays within the “player area” or the virtual bounding box that we set up for them. If not, we don’t execute the code in #7 that actually moves the player.
  6. Update the player’s position.
  7. Here we are checking to see if the player collides with any of the sprouts. Sprouts pose as obstacles for the player and we want to restrict the player’s movement if they are in his way.
  8. Finally, if there is a collision, revert the player’s position to their last good position.

Now if you run the game, you should be able to drag anywhere on your game area and move the player within the confined space.



Step 2: The Missile Object


The missile object is what allows the player and the other game objects to interact. The player will fire a constant stream of missiles with the speed and frequency varying on the current level.

Before we begin creating the Missile, we need to establish a few constants that will be used. Open GameConfig.h and add the following lines:

#define kMissileSpeed 1.0
#define kMissileMaxSpeed 10.0
#define kMissilesTotal 20
#define kMissileFrequency .6 //seconds
#define kMinMissileFrequency .2

I will explain each of these as they come up in the code that follows. Now, create a new GameObject subclass called Missile. Add the following code to Missile.h:

#import "cocos2d.h"
#import "GameObject.h"

@interface Missile : GameObject
@property (nonatomic, assign) BOOL dirty;
- (void)update:(ccTime)dt;
@end

The dirty property will be used in the future to denote that this missile is no longer in play. This could be because of it going off screen or colliding with another game object. Since the missiles are constantly moving, they will need an update method to animate them.

Now, open up Missile.m and add the following code:

#import "Missile.h"
#import "GameLayer.h"
#import "GameConfig.h"

@implementation Missile

@synthesize dirty = _dirty;

// 1
- (id)initWithGameLayer:(GameLayer *)layer {

if(self == [super initWithGameLayer:layer]) {
self.sprite = [CCSprite spriteWithSpriteFrameName:@"missile.png"];
}

return self;
}

- (void)update:(ccTime)dt {
// 2
int inc = kMissileSpeed * (self.gameLayer.level + 1.5);

// 3
if(inc > kMissileMaxSpeed) {
inc = kMissileMaxSpeed;
}

// 4
int y = self.position.y + inc;
self.position = ccp(self.position.x,y);

// 5
if(self.position.y > kGameAreaStartY + kGameAreaHeight) {
self.dirty = YES;
}
}

@end

  1. Our init method looks very familiar and is only responsible for creating the Missile’s sprite.
  2. This is how fast the missile will be moving. It starts with a base value and speeds up based on the current level.
  3. At some point, the speed of our missile might get out of control. We prevent this by adding a max speed.
  4. These two lines are what actually move the missile forward. We calculate a new y for the missile and update the position.
  5. Finally, if the missile collides with the top, set it’s _dirty property to true. We will garbage collect the dirty missiles inside of GameLayer.



Step 3: Firing The Missiles


Now that we have some missiles to fire, we need to fire them off from the player. Generally, when you have a large amount of objects such as missiles, you want to reuse as many as possible and not allocate new ones while the main loop is running. To solve this issue, we will create two arrays. One array will hold all of the missiles that are currently in play (ie fired by the player) and the other will hold the pool of missiles that have yet to be fired. At the end of the update method, we will clean up all of the dirty missiles and move them from the “in play” array to the “pool” array.

Add the following properties to your GameLayer.h file:

@property (nonatomic, retain) NSMutableArray *missilesWaiting;
@property (nonatomic, retain) NSMutableArray *missilesFiring;

Now open GameLayer.m, import Missile.h, and add the following lines in to your init method:

// 1
_missilesWaiting = [[NSMutableArray alloc] initWithCapacity:kMissilesTotal];
_missilesFiring = [[NSMutableArray alloc] initWithCapacity:kMissilesTotal];
// 2
for(int x = 0; x < kMissilesTotal; x++) {
Missile *missile = [[Missile alloc] initWithGameLayer:self];
[self.missilesWaiting addObject:missile];
[missile release];
}

  1. Initialize each of the missile arrays
  2. Loop kMissilesTotal times and create that many Missile objects. Once they are created, we add them to the missilesWaiting array.

Next, jump down to the update method and add the following code:

// 1
static float missleFireCount = 0;

- (void)update:(ccTime)dt {

// ...Caterpillar code...

// 2
float frequency = kMinMissileFrequency;
if(kMissileFrequency / (self.level * 1.25) > kMinMissileFrequency) {
frequency = kMissileFrequency / self.level;
}

// 3
if(missleFireCount < frequency) {
missleFireCount += dt;
} else {
missleFireCount = 0;
// 4
if([self.missilesWaiting count] > 0) {
Missile *missile = [self.missilesWaiting objectAtIndex:0];
[self.missilesFiring addObject:missile];
[self.missilesWaiting removeObjectAtIndex:0];
missile.position = self.player.position;
[self.spritesBatchNode addChild:missile.sprite];

}
}

// 5
__block Missile *dirty = nil;
[self.missilesFiring enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Missile *missile = (Missile *)obj;
[missile update:dt];
if(missile.dirty) {
dirty = missile;
*stop = YES;
}
}];

// 6
if(dirty) {
dirty.dirty = NO;
[self.missilesWaiting addObject:dirty];
[self.missilesFiring removeObject:dirty];
[self.spritesBatchNode removeChild:dirty.sprite cleanup:NO];
}
}

  1. We need to create a static counter to help facilitate the frequency at which the missiles are fired.
  2. Calculates the missile fire frequency. As the level increases, so does the frequency.
  3. We only want to release a new missile if the current frequency is greater than or equal to the specified frequency for the level
  4. Pulls a missile out of the waiting array (if there are any in there) and adds it to the firing array. It’s also at this stage that we add the missile’s sprite to the batch node to be drawn.
  5. Enumerates all of the missiles checking for dirty one’s. If we find one, remember which one it is so we can move it back to the waiting array.
  6. If there was a dirty missile, move it from the waiting to the firing array and remove it’s sprite from the batch node.

This is all of the code needed to animate the missiles. Go ahead and run the game at this point and watch the missiles fire from the player as you move around.

Missiles



Conclusion


Now that we have enabled some player and missile animations, it’s really starting to feel like a game. We also did some basic collision detection between the player object and the sprout object. In the next tutorial in the series, we will dig deeper into collision detection as we establish collisions between the missiles and the sprouts, missiles and the centipede, and player and the centipede.

Happy coding!

2011年12月21日星期三

Basic Security in iOS 5 Tutorial Part 1

Basic Security in iOS 5 Tutorial Part 1

This is a post by Chris Lowe, an iOS application developer and aspiring game developer living in San Antonio, Texas. He warns that this tutorial is pretty Epic in length, but promises you’ll learn a thing or two along the way. :]
Learn how to store passwords securely in the Keychain!
Learn how to store passwords securely in the Keychain!
One of the most important aspects of software development also happens to be considered one of the most mysterious and scary (and is thus avoided like the plague): that of securing an application.
Users expect and demand that applications run as intended and keep their data safe and secure, whether it be from intruders, other users, or even from the correct user making mistakes.
But app security, while it can be time-consuming, need not be scary or mysterious!
Good app security has a couple of qualifications:
  • Users must not consciously know they are being protected. (That is, don’t get in the way! Users aren’t there to evaluate your data security practices; they want to use your app!)
  • Your security must be difficult to work around or break. (Nothing is impossible to hack, given enough time and horsepower.)
  • Don’t be Citibank.
Luckily for us, Apple has created several APIs for our use to help make our apps the best they can be. These include:
  • Secure text entry
  • An encrypted keychain
  • Great hashing algorithms; and
  • The Data Protection API.
In this tutorial, we’re going to cover all of this and more, as we build an application to keep track of the holiday presents that we are going to buy our friends and family. We’ll call it “Christmas Keeper.”
As an added bonus, we’re going to use TONS of awesome new iOS5 features, including Twitter, Storyboards, ARC, JSON, Alert Views, Static Table Views, and a simple Custom UI.
So keep reading to learn more – by the end of this tutorial series, you will be a better, more security-conscious developer!

Getting Started (Plus, a Little Housekeeping)

Launch Xcode and create a new project with the iOS\Application\Single View Application template. Fill out the template fields as follows:
ChristmasKeeperTemplate
  • Product Name: ChristmasKeeper
  • Company Identifier: the identifier that you use for your apps, in reverse domain notation
  • Class Prefix: leave this empty
  • Device Family: iPhone
  • Use Storyboard: yes, please
  • Use Automatic Reference Counting: Ditto
  • Include Unit Tests: this should be unchecked
Ok, we have our project setup with all of the default settings. This is a great start, but it doesn’t make our app great, so let’s make a few tweaks.
First, download the images we are going to be using and drag and drop them into the project.
Now on the Project Summary page, you should see that Xcode already picked up the Default and Default@2x.png files for your splash images. Drag the Icon.png and Icon@2x.png files into their respective App Icons boxes (Xcode will complain about the images, but just click Yes).
CKSettings
While we are on this screen, scroll down (expand if necessary) to the Linked Framework and Libraries section. Go ahead and add the Twitter and Security Frameworks here.
CKFrameworks
Jump over to the Info tab (at the top of the Project Settings). Expand the “Icon Files (iOS 5)” option and the Primary Icons option. Take a second and change “Icon already includes gloss effect” to YES.
In Xcode 4.2/iOS5, Apple decided that you could have some icons with and without icon gloss so the generic item of “Icon already includes gloss effect” – that you would put as a new key on the root level – no longer applies.
Also, while you’re here, change the “Bundle Display Name” to something more friendly, like “Christmas” for example, or even something more sneaky like “Boring App” to throw off any spies. :]
Lastly, add a new key (by selecting the last entry and clicking the + button that appears). Select “Status bar is initially hidden” from the drop down, make sure the type is set to BOOL, and set it to YES. This will give us maximum screen real estate for our app.
CKInfo
Our tweaking here is done! Go ahead and hit Build and Run to make sure we didn’t fudge anything.
Christmas Keeper Launch Image

Storyboard Magic

One of the coolest parts of iOS5 is Storyboards. With it, we can mock up an entire application in a matter of minutes and, best of all, we don’t have to deal with the Application Delegate, Navigations Controllers, Tab Bar Controllers, or any other messy stuff that can waste a lot of development time!
So let’s head into the MainStoryboard.storyboard file and dig in. We are going to spend a bit of time here, so bear with me. It will be well worth it!
This is what our app is going to look like:
CKStoryboard
The default Storyboard is kind enough to give us a blank UIViewController to start with, so let’s be gracious hosts and use it! This view will serve as our landing view when the app is launched, and will be where we prompt the user for their PIN.
Add a UIImageView to the Controller and let it expand to the size of the window. If you happen to have a status bar still showing, snip that by going to the Attributes Inspector and changing the Status Bar Simulated Metric to None.
Set the image on the UIImageView to Default.png. iOS should auto-detect if you are on the Retina Display and change the graphic for us, since one is available.
CKLaunchImage
Next, drop a UITableViewController onto the Storyboard. It’s kind of ugly and it needs a title. So let’s put it in a Navigation Controller!
Do this by using the new “Embed In…” feature of Interface Builder. With the Table View selected, go to Editor menu > Embed In… > Navigation Controller. You’ll notice that a new Navigation Controller is added and automatically linked to the Table View.
CKEmbedIn
Now, let’s spice it up a little bit with some color. Select the Navigation Controller, then the Navigation Bar (you have to be zoomed in to 100% level to select it) and change its tint to green (you might need to select the Table View before its Nav Bar will pick up the color change). Then select the Navigation Bar on the Table View and set its title to “Christmas Presents.”
CKNavTitle
Let’s hook up the first View Controller we made with the new Table View. Control-Drag from the first View Controller (the one with the Image View on it) to the Navigation Controller. You can also drag it to the Table View Controller but I find it easier to understand this way.
Select Modal as the Segue type, then select the newly created Segue and change its transition style to Cross Dissolve. Set the Identifier as “ChristmasTableSegue.”
We’re going to create a custom Table View cell right inside of the Storyboard, and we’re going to use the one that is already provided for us from when we dropped in the UITableViewController. Select the white box below the “Prototype Cells” header and set the height to 90px. Set the Identifier to “ChristmasListCell,” and the Accessory type to Disclosure Indicator.
CKTableCell
Now drag a UIImageView onto the cell. Set the width and height to 90px, move it to the left corner (you’ll see all of the nice blue alignment lines appear), set the Image to “present.png”, and set the View Mode to Aspect Fit.
Then add a UILabel next to the image and set the width to 202 and the height to 90 (this should fill in nicely from the edge of the image to the Disclosure Indicator, again with the alignment lines appearing). Set the number of lines to 0 and set the font to custom, Helvetica Neue Light, size 14.
One last quick step here: add a UIBarButtonItem to the Navigation Bar on the Table View and set it to the “Add” Identifier.
CKCellArrows
Ok, take a breath. Blink a few times. We have a few more steps, and then our UI will be DONE! All thanks to the power of Storyboards!
Drag out another UITableViewController and embed it inside of a Navigation Controller, just like the last one. Set the Tint on this Controller as well. Maybe a nice festive red would fit the bill?
Next, create a Segue from the + (Add) UIBarButtonItem you added to the Christmas Presents Table and Control-Drag to the new Navigation Controller. Use a Modal action again, except leave the default Transition Style (we want it to pop up like normal). Set this segue’s Identifier to “AddChristmasPresent.”
Give the new UITableViewController a title of “New Present” and add “Cancel” and “Done” Bar Button Items.
Now, select the entire Table View, set it to Static and of type Grouped. It will give you three cells to work with, but we only need two, so delete one of the extras.
Select the first table cell, expand it to 236px, set the Identifier to NewPresentImageCell, and the Selection Style to None. Add a UIImageView to the cell, size 300×236; set the Aspect Fit and Image to “present.png.”
Select the second table cell, expand it to 156px, set the Identifier to NewPresentTextCell, and the Selection Style to None. Add a UITextView to that cell, size 300×156. Set the font to Custom, Helvetica Neue Light, size 14 here as well. Set the Return key to Done, and the default text to “Enter the details of your Christmas Present here!”
CKAddPresent
Finally, we want to view the presents that we have on the List. We want to view them in the same way that we added them, so we’ll cheat here and copy the “Add Present” Table View and reuse it as the “Present Details” Table View. To do that, click on the Table View Controller inside of the New Present Scene, and copy and paste it back into the Storyboard.
CKTableCopy
You’ll notice that it is pasted overtop of the Add Present Table View. Drag it off to its own spot and create a Segue from the Christmas Presents table cell to this view, selecting Push as the action. Set the Identifier to “ChristmasDetailsSegue.”
You should see the Table View pick up the existing Navigation Controller and color. Just a few changes needed here – remove the Cancel button, change the Done button to an Action button, change the title to “Present Details,” and uncheck “Editable” in the UITextView.
There, those are all of the changes you need to reuse the “Add Present” Table View as the “Present Details” Table View!
Lastly, hit Build and Run to make sure we didn’t break anything in the process. Of course, none of the transitions will work because we haven’t finished coding them yet, but we have the scaffolding in place!

Time To Code!

Enough with the Storyboard editor for now – let’s code something before we go cross-eyed hooking up Segues and tweaking table view cells! :]
We’ll start with the first View Controller that we tweaked in the Storyboard. Create a new file with the iOS\Cocoa Touch\UIViewController subclass template, name it ChristmasRootViewController, and make it a subclass of UIViewController. Leave the bottom two options unchecked.
Open ChristmasRootViewController.h and add a property for a BOOL that will tell us whether the user is authenticated. Call it “pinValidated.” Also, since we are going to be using several text fields in this class, go ahead and add yourself as a UITextField delegate ().
#import <UIKit/UIKit.h>
 
@interface ChristmasRootViewController : UIViewController <UITextFieldDelegate>
 
@property (nonatomic) BOOL pinValidated;
 
@end
Jump over to ChristmasRootViewController.m and synthesize the property we just created:
@synthesize pinValidated;
Next add the implementations for viewDidLoad and viewDidAppear:
#pragma mark - View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.pinValidated = NO;
}
 
- (void)viewDidAppear:(BOOL)animated 
{
    [super viewDidAppear:animated];
    [self presentAlertViewForPassword];
}
Two lines of code were added here. First we initialize our pinValidated property to NO. Then, once our view is on the screen, we call a method called presentAlertViewForPassword.
What does this do? Well, exactly as the method signature indicates, we are going to prompt the user for their PIN if they have one, or require them to set one up if they don’t. Add this above those two methods:
- (void)presentAlertViewForPassword 
{
 
    // 1
    BOOL hasPin = [[NSUserDefaults standardUserDefaults] boolForKey:PIN_SAVED];
 
    // 2
    if (hasPin) {
        // 3
        NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:USERNAME];
        NSString *message = [NSString stringWithFormat:@"What is %@'s password?", user];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Enter Password" 
                                                        message:message  
                                                       delegate:self 
                                              cancelButtonTitle:@"Cancel" 
                                              otherButtonTitles:@"Done", nil];
        // 4
        [alert setAlertViewStyle:UIAlertViewStyleSecureTextInput]; // Gives us the password field
        alert.tag = kAlertTypePIN;
        // 5
        UITextField *pinField = [alert textFieldAtIndex:0];
        pinField.delegate = self;
        pinField.autocapitalizationType = UITextAutocapitalizationTypeWords;
        pinField.tag = kTextFieldPIN;
        [alert show];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Setup Credentials" 
                                                        message:@"Secure your Christmas list!"  
                                                       delegate:self 
                                              cancelButtonTitle:@"Cancel" 
                                              otherButtonTitles:@"Done", nil];
        // 6
        [alert setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
        alert.tag = kAlertTypeSetup;
        UITextField *nameField = [alert textFieldAtIndex:0];
        nameField.autocapitalizationType = UITextAutocapitalizationTypeWords;
        nameField.placeholder = @"Name"; // Replace the standard placeholder text with something more applicable
        nameField.delegate = self;
        nameField.tag = kTextFieldName;
        UITextField *passwordField = [alert textFieldAtIndex:1]; // Capture the Password text field since there are 2 fields
        passwordField.delegate = self;
        passwordField.tag = kTextFieldPassword;
        [alert show];
    }
}
This looks like a lot of code, but actually it’s quite simple. Let’s go over it step by step.
  1. First we check if the user has set up a PIN before. We do that by checking for a BOOL that we saved to the NSUserDefaults. Notice that we are checking for a key called PIN_SAVED. That seems kind of odd – it’s actually a macro from a Constants class we will get to in a moment.
  2. Then we evaluate if we have the BOOL or not. If we do, that means the user has launched this app before and gone through the setup process. If not, then the user hasn’t been here or setup the PIN before, so let’s prompt him again.
  3. Next we get the user’s name, also stored in NSUserDefaults, and then we ask “What is [your name here]‘s password?” Notice we also assign a value to alert.tag, from an enum also in the Constants class.
  4. A great new feature in iOS5 is that we now have multiple types of UIAlertViews at our disposal! Here we are going to use the UIAlertViewStyleSecureTextInput type, which simply gives us an alert view with a text field for entering a password.
  5. Another great new thing in iOS5: out of the box, we get access to the UITextFields that are shown in an alert view! No more hacks to navigate the view hierarchy, etc. Notice that the UIAlertView class now has a nice method for us called “textFieldAtIndex,” which gives us the UITextFields available to us! Also, we can do ANYTHING that you can do on a normal UITextField – here we are setting the delegate, the capitalization settings, and the tag.
  6. Like #4 above, we are going to use another new Alert View style, but this time have two text fields for a user name and password. Again, we can customize the UITextField to our liking. So, for example, you could set the keyboard type on the Password input if you want to restrict the password to numbers only.
OK, from here let’s create our Constants class (this will house all of our Macros, enums, etc.), update our Storyboard, then hit our first real Build and Run!
For the Constants class, create a new file with the iOS\Cocoa Touch\Objective-C class template, set the class as ChristmasConstants, and make it a subclass of NSObject. For this tutorial, we only need the .h, so you can delete the .m.
Then replace ChristmasConstants.h with the following:
// Used for saving to NSUserDefaults that a PIN has been set, and is the unique identifier for the Keychain.
#define PIN_SAVED @"hasSavedPIN"
 
// Used for saving the user's name to NSUserDefaults.
#define USERNAME @"username"
 
// Used to specify the application used in accessing the Keychain.
#define APP_NAME [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"]
 
// Used to help secure the PIN.
// Ideally, this is randomly generated, but to avoid the unnecessary complexity and overhead of storing the Salt separately, we will standardize on this key.
// !!KEEP IT A SECRET!!
#define SALT_HASH @"FvTivqTqZXsgLLx1v3P8TGRyVHaSOB1pvfm02wvGadj7RLHV8GrfxaZ84oGA8RsKdNRpxdAojXYg9iAj"
 
// Typedefs just to make it a little easier to read in code.
typedef enum {
    kAlertTypePIN = 0,
    kAlertTypeSetup
} AlertTypes;
 
typedef enum {
    kTextFieldPIN = 1,
    kTextFieldName,
    kTextFieldPassword
} TextFieldTypes;
Basically, all this file does is contain strings that we’ll use throughout the application.
We use enums here (remember our ChristmasKeeperRootViewController class) so that we can easily identify the Alert Type. We don’t have to remember that 0 means password only and 1 means username/password. The same goes for the TextFieldTypes enum.
Ignore the SALT_HASH meaning for now – we’ll get to that soon.
Now, go back to ChristmasRootViewController.h and import this class:
#import "ChristmasConstants.h"
Finally, jump back to the MainStoryboard.storyboard, select our first View Controller, and set its Class type under the Identity Inspector to ChristmasKeeperRootViewController (its likely still set to ViewController by default).
w00t – it’s finally time to BUILD AND RUN!!! When it starts up you should see a nice popup appear:
CKAlertSetup

Do Not Pass Alert View, Do Not Collect $200

So far so good, except there’s one small problem – it doesn’t do anything!
As you’ve probably surmised by now, we need to handle the user entering text input as well as hitting the buttons from the Alert View. Luckily, there is an easy fix to this problem – delegate methods!!
We get textFieldDidEndEditing: and alertView:didDismissButtonWithIndex: methods sent to us for FREE, and all we had to do was pay postage and shipping (and by that, I mean setting ourselves as the delegate).
Lets start with the Alert View delegate method. Add this inside ChristmasRootViewController.m:
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex 
{
    if (alertView.tag == kAlertTypePIN) {
        if (buttonIndex == 1 && self.pinValidated) { // User selected "Done"
            [self performSegueWithIdentifier:@"ChristmasTableSegue" sender:self];
            self.pinValidated = NO;
        } else { // User selected "Cancel"
            [self presentAlertViewForPassword];
        }
    } else if (alertView.tag == kAlertTypeSetup) {
        if (buttonIndex == 1 && [self credentialsValidated]) { // User selected "Done"
            [self performSegueWithIdentifier:@"ChristmasTableSegue" sender:self];
        } else { // User selected "Cancel"
            [self presentAlertViewForPassword];
        }
    }
}
Remember that enum (enumerator for you more literal types) that we created from our ChristmasConstants class? Well, now it definitely comes in handy since we can easily (as reading humans) understand which Alert View we are talking about – just the password Alert View or the alert with username/password.
So first we check which view it is. Done. Then we check to see if the user hit the “Done” button AND if what was entered is correct.
If we fail that check, we prompt the user again for their credentials because we must authenticate someone. If we pass the check, however, we let them through. We do this via a performSegueWithIdentifier: sender: method, which will kick off our Cross Dissolve modal view that we created (way) earlier.
So now we have handled the Alert View. But “Wait!” you say. “How did we get pinValidated to YES, or validate the credentials the user entered?” The latter problem is simple to solve: we check for an existing username and password that has been written to the NSUserDefaults.
Add this right above alertView:didDismissWithButtonIndex:
// Helper method to congregate the Name and PIN fields for validation.
- (BOOL)credentialsValidated 
{
    NSString *name = [[NSUserDefaults standardUserDefaults] stringForKey:USERNAME];
    BOOL pin = [[NSUserDefaults standardUserDefaults] boolForKey:PIN_SAVED];
    if (name && pin) {
        return YES;
    } else {
        return NO;
    }
}
That takes care of the credentials check (used for first time setup), but what about pinValidated? This is where the textField delegate method comes in to save the day – and we finally get to see some security code!
Add the following method to ChristmasRootViewController.m:
#pragma mark - Text Field + Alert View Methods
- (void)textFieldDidEndEditing:(UITextField *)textField 
{
    // 1
    switch (textField.tag) {
        case kTextFieldPIN: // We go here if this is the 2nd+ time used (we've already set a PIN at Setup).
            NSLog(@"User entered PIN to validate");
            if ([textField.text length] > 0) {
                // 2
                NSUInteger fieldHash = [textField.text hash]; // Get the hash of the entered PIN, minimize contact with the real password
                // 3
                if ([KeychainWrapper compareKeychainValueForMatchingPIN:fieldHash]) { // Compare them
                    NSLog(@"** User Authenticated!!");
                    self.pinValidated = YES;
                } else {
                    NSLog(@"** Wrong Password :(");
                    self.pinValidated = NO;
                }
            }
            break;
        case kTextFieldName: // 1st part of the Setup flow.
            NSLog(@"User entered name");
            if ([textField.text length] > 0) {
                [[NSUserDefaults standardUserDefaults] setValue:textField.text forKey:USERNAME];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
            break;
        case kTextFieldPassword: // 2nd half of the Setup flow.
            NSLog(@"User entered PIN");
            if ([textField.text length] > 0) {
                NSUInteger fieldHash = [textField.text hash];
                // 4
                NSString *fieldString = [KeychainWrapper securedSHA256DigestHashForPIN:fieldHash];
                NSLog(@"** Password Hash - %@", fieldString);
                // Save PIN hash to the keychain (NEVER store the direct PIN)
                if ([KeychainWrapper createKeychainValue:fieldString forIdentifier:PIN_SAVED]) {
                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:PIN_SAVED];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    NSLog(@"** Key saved successfully to Keychain!!");
                }                
            }
            break;
        default:
            break;
    }
}
There’s a lot to take in here, so let’s step through it together.
  1. First we use our enum again to determine which UITextField we are talking about.
  2. Get the “hash” of our password. A “hash” is simply a fixed-length number generated from another number or string (in our case, the user’s password). We’ll discuss more about why we’re using hashes in a second.
  3. Here we invoke a method called “compareKechainValeuForMatchingPIN:” from a class called KeychainWrapper. We should implement this so that you can see what it does. :] Right now, what you need to know is that it returns a BOOL of whether the value that the user entered matches what we have saved. If it does, then pinValidated is YES, else NO.
  4. We do something similar to step #3, but this time we are generating the hash ourselves and saving that to the NSUserDefaults for our future use.
After reading the above code block, you might think to yourself, “why bother with all of this hash business, and not just use the password directly?”
Storing a user’s password directly is always a bad idea. If you do so, it gives a malicious user or attacker the potential capability of retrieving the user’s raw password, which could lead to all sorts of problems for your users.
Very Important: If you learn nothing else from this tutorial, learn this: NEVER, EVER, EVER, THEN ANOTHER EVER, store the password directly. ALWAYS use some other means of hiding the user’s password, such as a hash – it still uniquely identifies what the user entered, but is not the plain value in clear text.
The same can go for the username, but it is more generally accepted that this can be less restrictive. You also want to apply this to sensitive data like credit card numbers, Social Security numbers, dates of birth – really anything that your user may not want easily exposed.
OK, so now that you know how the overall plan works, let’s implement the security code in the KeychainWrapper class so that we can see this thing in action!
Create a new file with the iOS\Cocoa Touch\Objective-C class template, enter KeychainWrapper for the Class, and make it a subclass of NSObject. Open up KeychainWrapper.h and replace it with the following:
#import <Foundation/Foundation.h>
#import <Security/Security.h>
#import <CommonCrypto/CommonHMAC.h>
 
@interface KeychainWrapper : NSObject
 
// Generic exposed method to search the keychain for a given value. Limit one result per search.
+ (NSData *)searchKeychainCopyMatchingIdentifier:(NSString *)identifier;
 
// Calls searchKeychainCopyMatchingIdentifier: and converts to a string value.
+ (NSString *)keychainStringFromMatchingIdentifier:(NSString *)identifier;
 
// Simple method to compare a passed in hash value with what is stored in the keychain.
// Optionally, we could adjust this method to take in the keychain key to look up the value.
+ (BOOL)compareKeychainValueForMatchingPIN:(NSUInteger)pinHash;
 
// Default initializer to store a value in the keychain.  
// Associated properties are handled for you - setting Data Protection Access, Company Identifer (to uniquely identify string, etc).
+ (BOOL)createKeychainValue:(NSString *)value forIdentifier:(NSString *)identifier;
 
// Updates a value in the keychain. If you try to set the value with createKeychainValue: and it already exists,
// this method is called instead to update the value in place.
+ (BOOL)updateKeychainValue:(NSString *)value forIdentifier:(NSString *)identifier;
 
// Delete a value in the keychain.
+ (void)deleteItemFromKeychainWithIdentifier:(NSString *)identifier;
 
// Generates an SHA256 (much more secure than MD5) hash.
+ (NSString *)securedSHA256DigestHashForPIN:(NSUInteger)pinHash;
+ (NSString*)computeSHA256DigestForString:(NSString*)input;
 
@end
This class is going to do two things for us:
  • Handle read/writes to/from the keychain.
  • Manage our encryption generation methods.
Next switch to KeychainWrapper.m and add the implementation. I’m going to give you all the code at once (and there’s a lot of it!) but don’t worry – we’ll go over it in detail afterwards (plus it has a ton of comments):
#import "KeychainWrapper.h"
#import "ChristmasConstants.h"
 
@implementation KeychainWrapper
// *** NOTE *** This class is ARC compliant - any references to CF classes must be paired with a "__bridge" statement to 
// cast between Objective-C and Core Foundation Classes.  WWDC 2011 Video "Introduction to Automatic Reference Counting" explains this.
// *** END NOTE ***
+ (NSMutableDictionary *)setupSearchDirectoryForIdentifier:(NSString *)identifier {
 
    // Setup dictionary to access keychain.
    NSMutableDictionary *searchDictionary = [[NSMutableDictionary alloc] init];  
    // Specify we are using a password (rather than a certificate, internet password, etc).
    [searchDictionary setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
    // Uniquely identify this keychain accessor.
    [searchDictionary setObject:APP_NAME forKey:(__bridge id)kSecAttrService];
 
    // Uniquely identify the account who will be accessing the keychain.
    NSData *encodedIdentifier = [identifier dataUsingEncoding:NSUTF8StringEncoding];
    [searchDictionary setObject:encodedIdentifier forKey:(__bridge id)kSecAttrGeneric];
    [searchDictionary setObject:encodedIdentifier forKey:(__bridge id)kSecAttrAccount];
 
    return searchDictionary; 
}
 
+ (NSData *)searchKeychainCopyMatchingIdentifier:(NSString *)identifier 
{
 
    NSMutableDictionary *searchDictionary = [self setupSearchDirectoryForIdentifier:identifier];
    // Limit search results to one.
    [searchDictionary setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
 
    // Specify we want NSData/CFData returned.
    [searchDictionary setObject:(__bridge id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
 
    // Search.
    NSData *result = nil;   
    CFTypeRef foundDict = NULL;
    OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)searchDictionary, &amp;foundDict);
 
    if (status == noErr) {
        result = (__bridge_transfer NSData *)foundDict;
    } else {
        result = nil;
    }
 
    return result;
}
 
+ (NSString *)keychainStringFromMatchingIdentifier:(NSString *)identifier 
{
   NSData *valueData = [self searchKeychainCopyMatchingIdentifier:identifier];
    if (valueData) {
        NSString *value = [[NSString alloc] initWithData:valueData
                                                   encoding:NSUTF8StringEncoding];
        return value;
    } else {
        return nil;
    }
}
 
+ (BOOL)createKeychainValue:(NSString *)value forIdentifier:(NSString *)identifier 
{
 
    NSMutableDictionary *dictionary = [self setupSearchDirectoryForIdentifier:identifier];
    NSData *valueData = [value dataUsingEncoding:NSUTF8StringEncoding];
    [dictionary setObject:valueData forKey:(__bridge id)kSecValueData];
 
    // Protect the keychain entry so it's only valid when the device is unlocked.
    [dictionary setObject:(__bridge id)kSecAttrAccessibleWhenUnlocked forKey:(__bridge id)kSecAttrAccessible];
 
    // Add.
    OSStatus status = SecItemAdd((__bridge CFDictionaryRef)dictionary, NULL);
 
    // If the addition was successful, return. Otherwise, attempt to update existing key or quit (return NO).
    if (status == errSecSuccess) {
        return YES;
    } else if (status == errSecDuplicateItem){
        return [self updateKeychainValue:value forIdentifier:identifier];
    } else {
        return NO;
    }
}
 
+ (BOOL)updateKeychainValue:(NSString *)value forIdentifier:(NSString *)identifier 
{
 
    NSMutableDictionary *searchDictionary = [self setupSearchDirectoryForIdentifier:identifier];
    NSMutableDictionary *updateDictionary = [[NSMutableDictionary alloc] init];
    NSData *valueData = [value dataUsingEncoding:NSUTF8StringEncoding];
    [updateDictionary setObject:valueData forKey:(__bridge id)kSecValueData];
 
    // Update.
    OSStatus status = SecItemUpdate((__bridge CFDictionaryRef)searchDictionary,
                                    (__bridge CFDictionaryRef)updateDictionary);
 
    if (status == errSecSuccess) {
        return YES;
    } else {
        return NO;
    }
}
 
+ (void)deleteItemFromKeychainWithIdentifier:(NSString *)identifier 
{
    NSMutableDictionary *searchDictionary = [self setupSearchDirectoryForIdentifier:identifier];
    CFDictionaryRef dictionary = (__bridge CFDictionaryRef)searchDictionary;
 
    //Delete.
    SecItemDelete(dictionary);
}
 
 
+ (BOOL)compareKeychainValueForMatchingPIN:(NSUInteger)pinHash 
{
 
    if ([[self keychainStringFromMatchingIdentifier:PIN_SAVED] isEqualToString:[self securedSHA256DigestHashForPIN:pinHash]]) {
        return YES;
    } else {
        return NO;
    }    
}
 
// This is where most of the magic happens (the rest of it happens in computeSHA256DigestForString: method below).
// Here we are passing in the hash of the PIN that the user entered so that we can avoid manually handling the PIN itself.
// Then we are extracting the username that the user supplied during setup, so that we can add another unique element to the hash.
// From there, we mash the user name, the passed-in PIN hash, and the secret key (from ChristmasConstants.h) together to create 
// one long, unique string.
// Then we send that entire hash mashup into the SHA256 method below to create a "Digital Digest," which is considered
// a one-way encryption algorithm. "One-way" means that it can never be reverse-engineered, only brute-force attacked.
// The algorthim we are using is Hash = SHA256(Name + Salt + (Hash(PIN))). This is called "Digest Authentication."
+ (NSString *)securedSHA256DigestHashForPIN:(NSUInteger)pinHash 
{
    // 1
    NSString *name = [[NSUserDefaults standardUserDefaults] stringForKey:USERNAME];
    name = [name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    // 2
    NSString *computedHashString = [NSString stringWithFormat:@"%@%i%@", name, pinHash, SALT_HASH];
    // 3
    NSString *finalHash = [self computeSHA256DigestForString:computedHashString];
    NSLog(@"** Computed hash: %@ for SHA256 Digest: %@", computedHashString, finalHash);
    return finalHash;
}
 
// This is where the rest of the magic happens.
// Here we are taking in our string hash, placing that inside of a C Char Array, then parsing it through the SHA256 encryption method.
+ (NSString*)computeSHA256DigestForString:(NSString*)input 
{
 
    const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:input.length];
    uint8_t digest[CC_SHA256_DIGEST_LENGTH];
 
    // This is an iOS5-specific method.
    // It takes in the data, how much data, and then output format, which in this case is an int array.
    CC_SHA256(data.bytes, data.length, digest);
 
    // Setup our Objective-C output.
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
 
    // Parse through the CC_SHA256 results (stored inside of digest[]).
    for(int i = 0; i &lt; CC_SHA256_DIGEST_LENGTH; i++) {
        [output appendFormat:@&quot;%02x&quot;, digest[i]];
    }
 
    return output;
}
 
@end
By the time you get to this line of text, you may be shaking or cross-eyed, or feeling uneasy about your future as a security-conscious developer!
It’s actually not that bad. Sure, it looks intimidating, but we’ll get through it in due time. For right now, let’s concentrate on the securedSHA256DigestHashForPIN method (second to last method), which will actually create the value we are going to store in the keychain.
  1. First we get the name the user has entered. This is going to be paired with other values to uniquely create our key and add some extra security to it. Then we Percent Escape the name to avoid any attempted attacks with special characters, etc. The iOS Keychain is UTF8 compliant (only), so we baseline everything to that.
  2. Next, we piece together the user’s name, the hash of the value they entered for their password, and the SALT_HASH string from our ChristmasConstants class. A “salt hash” is just an additional hash (remember, a hash is a fixed-length number based on a number or string) that can be used to augment and enhance the security of the password. The reason that you want to add this is to prevent what’s called a “dictionary attack,” where someone has a whole list of pre-defined passwords and goes about trying every one of them against your password field. If an attacker doesn’t know your salt hash, then they can never generate your password (provided your salt hash is long enough). To add more security, it would be better if it was generated randomly each time, but that’s another day’s tutorial!
  3. Once we have our strong hash built, we pass it over to our computeSHA256DigestForString: method so that we can harden our password even more before storing it.
Now take a look at the computeSHA256DigestForString: method. It takes in a string (like the one from our securedSHA256 method) and puts it inside of a C-Style Character Array. Then it turns around and makes an NSData object of the same size in preparation of the data coming back. The digest array will actually hold our data.
Then we use a convenient CC_SHA256 method (CC being CommonCrypto, Apple’s kind-of-but-not-too-friendly cryptography framework), in which we pass in the data to be encrypted, its length, and where we want the encrypted bytes to be stored.
Once that is done, we work backwards, extract the data out of the digest array, and build a string out of it. And that is what we return.
Just a dozen lines of code (or so) is all it takes to get a pretty strongly-defended password!
One last step – go to the top of ChristmasRootViewController.m and import the KeychainWrapper class:
#import "KeychainWrapper.h"
Let’s build this bad boy one more time to see our security abilities in action!
CKStart –> CKStart2 –> CKTable1
You should be able to run it and create a username and password, and run it a second time and use the same username and password to log in. And best of all, it’s done in a secure manner!

Where to Go From Here?

Here is an example project with all of the code from the tutorial series so far.
That wraps up Part One of this tutorial. To recap, we built out 99% of our UI and workflow via Storyboards, and then we worked on prompting the user for a password.
From a security perspective, you now know a bit about how to properly handle sensitive data, as well as how to generate strongly-encrypted data in order to provide maximum protection for your users. Remember, this is what they expect!
Stay tuned for part two of the series, where we wrap up this project with a few more security features and new iOS5 APIs. We’ve got a bit more explaining to do of what’s inside of the KeychainWrapper class, but I think you’ll find it a great tool for your arsenal of reusable code!
If you have any questions or comments on this tutorial or security in general, please join the discussion below!

This is a post by Chris Lowe, an iOS application developer and aspiring game developer living in San Antonio, Texas.