显示标签为“Code”的博文。显示所有博文
显示标签为“Code”的博文。显示所有博文

2011年11月29日星期二

Amazing Apple-like Documentation

Amazing Apple-like Documentation:

I know I know, Documentation is a bad bad word, especially for us creative people. The true creativity is in writing code, not in writing comments, isn’t it?

Well, regardless, you might find yourself in the situation that you want other people to reuse your code. Or better yet, a different self of you in a year should be able to understand your line of reasoning of today. If you do programming for a longer time you will pass the phase of being shocked at how bad your code was and then get into the phase of having no idea what you where thinking. So a liberal sprinkling of comments can help you get up to speed on your old code.


I invented a technique of chewing on a portion of a programming puzzle where you comment almost every line of code as if you were to explain to somebody the steps in your ingenious approach. Maybe somebody else coined a term for this, for me it helps me sort my thoughts. And probably will do the same a year or ten from now. So commenting comes naturally to me, Documentation by Comment-ation is a logical extension to the concept.

Readability

Apple has nicely written documentation for their APIs though their process of creating it is hard to duplicate for us solo or small team developers. Apple has an entire department that writes the documentation the “Apple Developer Publications Department”, googling for them you can even find a two-year-old style guide for writers. Just consider this quote from it on page 6 just to see how much over our heads this “proper documenting” is:

“In general, follow the style and usage rules in:

  • The American Heritage Dictionary
  • The Chicago Manual of Style
  • Words into Type

Exceptions to certain guidelines in these resources are noted in this guide.

In cases where reference sources conflict with each other, follow:

  • The Chicago Manual of Style for questions of style and usage
  • The American Heritage Dictionary for questions of spelling

Also refer to any department-specific materials provided by your editor.”

No way I’m going to start perusing a dictionary for my comments! And I guess neither will you…

Apple apparently is using the RenderX XEP engine to convert their own XML documentation to the nice PDF and HTML output you see online today. That’s the second reason why their process is out of reach for us.

Enter AppleDoc

One-person company Gentle Bytes saw our need for a simple and usable way to generate nice-to-look-at documentation from source code comments. So he started the AppleDoc open-source project in or around April 2009. It’s grown over 2 years and in January 2011 the version got bumped to 2.0. This is finally a full rewrite that no longer depends on Doxygen to parse the source code.

AppleDoc works such that it parses your source code and assembles the source comments in a structure strikingly similar to what we are used to from Apple. There is documentation as to how to construct your comments but I found it not very intuitive. So let me give you an overview and tutorial here as to what I learned to help you get up to speed as quickly as possible on using AppleDoc yourself.

Setup

You need to clone the AppleDoc Xcode project from github and build the command line tool. I assume that you have previously set up github on your development machine.

git clone git://github.com/tomaz/appledoc.git
cd appledoc
open appledoc.xcodeproj

In Xcode switch to the appledoc target and build it. You will see the appledoc entry in the Products group turn black.


Copy the appledoc command line utility to any folder in your path, I put it in /usr/local/bin. This way it is available regardless of what your current working directory is. To see that this is working and to see the appledoc help you can do “appledoc –help”.

Commenting Correctly

AppleDoc requires that you adhere to a certain style of commenting that is slightly different from the standard C comments you are used to, namely /* comment */ and // single line.

Classes and Categories

For every class or category that you are documenting, add one or more paragraphs of comments describing what the class is used for. This goes between the imports and the interface in the header file.

/** This class demonstrates AppleDoc.

A second paragraph comes after an empty line.

int i=0;
i++;

And some sample code can also be in a block, but indented with a TAB.
*/

Note the second asterisk on the opening of the comment. Paragraphs are separated by an empty line. All this text is parsed as markdown syntax, the inventor Gruber has an introduction. You can have sample code in the text as well, in it’s own block and indented with a tabulator. The above turns into a nicely formatted Overview section.

AppleDoc automatically turns anything looking like an Objective-C method into a cross-reference. That’s usually what we want, but will get you some warnings if you reference external classes in a sample block. See below how you can solve that.

Methods

The comment block before a method (again in header) will be turned into the description 0f the method. The default behavior is to use the first paragraph for the short description and all paragraphs for the “Discussion”. I disabled this repeating of the first paragraph because I find that it looks weird to have the same text twice, not like Apple.


/**---------------------------------------------------------------------------------------
* @name A name under which this method appears under "Tasks"
*  ---------------------------------------------------------------------------------------
*/

/** This is the first super-awesome method.

You can also add lists, but have to keep an empty line between these blocks.

- One
- Two
- Three

@param string A parameter that is passed in.
@return Whatever it returns.
*/
- (NSString *)someMethodWithString:(NSString *)string;

The comment block with the @name serves for the grouping of methods in the “Tasks” section at the beginning of the page for the class/category. You should group similar methods under one such section, you don’t have to repeat it because the @name is good until the next one. You see that you can also have lists (numbered or not). You need an @param for each parameter of the method. If it has a non-void return value then you also need an @return to describe that. Omitting any of these will get you a warning.


You see that the first paragraph of the description ended up at the top, the rest of it including the list went to the Discussion part.

Some more bells and whistles are possible, shown here:


/** This is the second super-awesome method.

Note that there are additional cool things here, like [direct hyperlinks](http://www.cocoanetics.com)

@param number A parameter that is passed in, almost as cool as someMethodWithString:
@return Whatever it returns.
@see someMethodWithString:
@warning *Warning:* A blue background.
@bug *Bug:* A yellow background.
*/
- (NSString *)someMethodWithInteger:(NSInteger)number;

This shows cross references inline and via the @see tag. For external hyperlinks you put the link words in square brackets, the link itself in round ones. Finally you have a choice of blue or yellow box for warnings/notices.


Unfortunately there is no support for constants, enums and other things you might want to put in your headers, but it’s being worked on as we speak. For now you should probably put the possible values for an typedef’d enum in a simple list.

Building the Docset and HTML

Once you have added sufficient commentary as outline above you will want to build the documentation. AppleDoc primarily builds docsets which are essentially bundles with a bunch of HTML and xml index files. These docsets integrate with your Xcode for easy browsing and searching.

It took me quite a bit of tweaking until I got the parameters right to get the output I wanted. Also there are apparently some bugs that manifest themselves if you have some switches in the wrong oder. For quick building I set up a Documentation target where I added a “Run Script” build phase to execute this script. This would just as well work in a separate shell script, though you’d have to substitute the actual path for the PROJECT_DIR.


/usr/local/bin/appledoc \
--project-name "DTFoundation" \
--project-company "Cocoanetics" \
--company-id "com.cocoanetics" \
--docset-atom-filename "DTFoundation.atom" \
--docset-feed-url "http://cocoanetics.github.com/DTFoundation/%DOCSETATOMFILENAME" \
--docset-package-url "http://cocoanetics.github.com/DTFoundation/%DOCSETPACKAGEFILENAME" \
--docset-fallback-url "http://cocoanetics.github.com/DTFoundation/" \
--output "~/help" \
--publish-docset \
--logformat xcode \
--keep-undocumented-objects \
--keep-undocumented-members \
--keep-intermediate-files \
--no-repeat-first-par \
--no-warn-invalid-crossref \
--ignore "*.m" \
--ignore "LoadableCategory.h" \
--index-desc "${PROJECT_DIR}/readme.markdown" \
"${PROJECT_DIR}"

Here are my reasons for the various switches:

  • project-name, project-company and company_id are standard
  • the atom filename and the urls are necessary to let the docset know where it can get an update
  • the output directory should be a place outside of your Xcode project. I found that having the generated documentation inside a github project does not make sense.
  • publish-docset causes AppleDoc to generate the Atom feed and xar archive file
  • logformat-xcode makes the output compatible with Xcode so that you get inline warnings
  • keep-intermediate-files is necessary to preserve the original HTML output which you can put on your server for online reading
  • no-repeate-first-par is the setting that does not duplicate the first paragraph into the discussion section
  • no-warn-invalid-crossref omits the annoying warnings that you get when AppleDoc cannot find a reference to class or method
  • we’re ignoring the .m files because otherwise AppleDoc would also try to get comments from these. We only want the comments from headers used also we don’t want the documentation say that a method was defined in the .h and the .m files which is unlike Apple.
  • the LoadableCategory.h is another file we explicitly need to ignore, it is a dummy class that forces the linker to also load certain tagged categories. No use having that in the documentation.
  • the index-desc is the path to a markdown file which additionally gets injected into the index page

The last switch is of special interest. Without it the index page of the docset is relatively barren. But since all of AppleDoc is based on markdown you can also re-purpose the readme file you usually have in the project root of your project as an introduction to the project. Write once, reuse: I’m loving it!

Publishing

AppleDoc will also install a generated docset into the same location where Apple’s docsets are residing. You can see these and install new ones via Xcode preferences, Downloads, Documentation tab.

You can add docsets on this screen via the plus button and by specifying the URL of the Atom feed. Remember, AppleDoc can generate this feed for you. If you leave the generated output in the publish folder around and update the project version then AppleDoc will add the new version to the feed file. So all you need is to copy the xar and the atom files to your web server after making sure that you specified the URLs correctly. This way somebody only needs to have the URL of the atom feed to install the docset.

The contents of the html folder in your output directory contain a full HTML site for the entire documentation. You can upload that to your web site as well, it is essentially the same content as in the docset. If you do, then people can browse the documentation outside of Xcode and you can also specify the URL there as fallback URL in your docset.

GitHub has a mechanism called GitHub Pages which you can enable via the admin area of every project. Once enabled you can put the web server files into a gh-pages branch of your open-source project. I finally got it working as well, but it is a bit weird having to constantly move around between the master and the gh-pages branch.

Conclusion

By adopting the described style of commenting methods and classes/categories you immediately reap the benefit of being able to generate beautiful docsets and HTML documentation. You can also inject your additional markdown files to enhance the index or even going as far as adding custom images and full HTML files. Development on AppleDoc continues – although slowly – and we’re looking forward to getting support for other things we’d like to document: notifications, protocols, enums and constants.

The main advantage of AppleDoc is that the comments also enhance your source code, so that even people without Xcode can read what you wrote. This way other developers benefit because they can look up your methods and see what your thoughts where. Often the availability of documentation is what many people use to decide whether or not they should add a dependency on your library or framework.

Finally it is yourself who will benefit in the long run because your commentary will allow you to understand what you where thinking many years ago. Don’t discount this possibility, we all get older all the time.

2011年11月10日星期四

Cocos2d Sprite Tutorial Part 3

Cocos2d Sprite Tutorial Part 3:
So in Part 2 we introduced an animated dragon that had 8 directions of movement and was completely controllable via touching the screen. Isn’t cocos2d awesome! Well today we’re going to do a little more, today we’re going to create some villagers – tons of them in fact. We’ll use the information we’ve gotten so far including loading sprites from a sprite sheet and setting up animations.

Source Code after the break!



Source code to this tutorials can be downloaded here: Sprite Tutorial Part 3 Source Code

So what are we building – Lets take a quick look at what our finished product is going to look like:



That’s a crap load of villagers and still at 60 fps because of the optimizations we’ve done in part 2 of the tutorial. So how does it all work? Well lets get right into it shall we.

We’re going to start by creating our adventurer class – This will store the CCSprite instance as well as our moving and walking animations. We’ll be creating a new Adventurer instance for each and every little character on the screen.

Adventurer.h

#import "cocos2d.h"

@interface Adventurer : CCNode {
CCSprite *_charSprite;
CCAction *_walkAction;
CCAction *_moveAction;
BOOL _moving;
}

@property (nonatomic, retain) CCSprite *charSprite;
@property (nonatomic, retain) CCAction *walkAction;
@property (nonatomic, retain) CCAction *moveAction;

@end

We could have subclass’d CCSprite if we wanted and then we could call “initWithFile” directly instead of having to initialize the Adventure class first, however, I feel like it’s better to get into the habit of keeping your sprite instances separate.

Adventurer.m

#import "Adventurer.h"

@implementation Adventurer

@synthesize charSprite = _charSprite;
@synthesize moveAction = _moveAction;
@synthesize walkAction = _walkAction;

-(id) init{
self = [super init];
if (!self) {
return nil;
}

return self;
}

- (void) dealloc
{
self.charSprite = nil;
self.walkAction = nil;
self.moveAction = nil;
[super dealloc];
}

@end

Basic initializer and we’ve included a dealloc function that will be called if and when we kill off the adventurer class instance – All of the things we’ve seen before. This is a very good example of a basic class that you can easily work with. Always make sure if you “retain” and object you have some game plan to release the memory later on. It’s easy to get sloppy, so do you best to resist the urge and sooner or later you won’t know any other way.

Now that we have the characters, lets use them in some way… Time to go back to our “PlayLayer.h” that we’ve seen in part 1 and 2 and make some changes…

#import "cocos2d.h"

#import "SceneManager.h"
#import "Adventurer.h"

@interface PlayLayer : CCLayer {
CCTexture2D *_texture;
CCSpriteSheet *_spriteSheet;

NSMutableArray *_charArray;
}

@property (nonatomic, assign) CCTexture2D *texture;
@property (nonatomic, assign) CCSpriteSheet *spriteSheet;

@property (nonatomic, retain) NSMutableArray *charArray;

@end

Well we’ve added the “Adventurer.h” import and now have 3 class variables now that we want to keep track of. The first is the “_texture” variable which will be loading in the adventurer sprite sheet – The next is the “_spritesheet” which is that batch processing for all those CCSprites that we’re going to be creating. Finally we want to be able to keep track of all our adventurers, so we have an array of them called “_charArray”. You can also see we’re setting the @property values for them as well so we can indirectly reference them in PlayLayer.m

Ok Now we get to the bulk of the class. Don’t worry we’ll break it down right afterwards – first lets write it out in all it’s glory.

PlayLayer.m

#import "PlayLayer.h"
#import "Adventurer.h"

@implementation PlayLayer

@synthesize texture = _texture;
@synthesize spriteSheet = _spriteSheet;

@synthesize charArray = _charArray;

enum {
kTagSpriteSheet = 1,
};

-(id) init{
self = [super init];
if (!self) {
return nil;
}

CCSprite *background = [CCSprite spriteWithFile:@"Terrain.png"];
background.position = ccp(160, 240);
[self addChild:background];

_texture = [[CCTextureCache sharedTextureCache] addImage:@"adventurer.png"];
_spriteSheet = [CCSpriteSheet spriteSheetWithTexture:self.texture capacity:100];
[self addChild:_spriteSheet z:0 tag:kTagSpriteSheet];

self.charArray = [[NSMutableArray alloc] init]; 

[self schedule:@selector(gameLogic:) interval:1.0f];

return self;
}

-(void)addAdventurer {

NSLog(@"Add Adventurer");

NSMutableArray *animFrames = [NSMutableArray array];

[animFrames removeAllObjects];

for (int i = 0; i < 9; i++) {
CCSpriteFrame *frame = [CCSpriteFrame frameWithTexture:self.texture rect:CGRectMake(i*16, 0, 16, 29) offset:CGPointZero];
[animFrames addObject:frame];
}

Adventurer * adventurer = [[[Adventurer alloc] init] autorelease];
if (adventurer != nil) {
CCSpriteFrame *frame1 = [CCSpriteFrame frameWithTexture:self.texture rect:CGRectMake(0, 0, 19, 29) offset:CGPointZero];
adventurer.charSprite = [CCSprite spriteWithSpriteFrame:frame1];

CGSize s = [[CCDirector sharedDirector] winSize];

int minY = adventurer.charSprite.contentSize.height/2;
int maxY = s.height - adventurer.charSprite.contentSize.height/2;
int rangeY = maxY - minY;
int actualY = (arc4random() % rangeY) + minY;

int minX = -300;
int maxX = 0;
int rangeX = maxX - minX;
int actualX = (arc4random() % rangeX) + minX;

adventurer.charSprite.position = ccp(actualX, actualY);

CCAnimation *animation = [CCAnimation animationWithName:@"walk" delay:0.2f frames:animFrames];
CCAnimate *animate = [CCAnimate actionWithAnimation:animation restoreOriginalFrame:NO];
CCSequence *seq = [CCSequence actions: animate,
nil];
adventurer.walkAction  = [CCRepeatForever actionWithAction: seq ];  

id actionMove = [CCMoveTo actionWithDuration:10.0f position:ccp(s.width + 200,actualY)];
id actionMoveDone = [CCCallFuncND actionWithTarget:self selector:@selector(spriteMoveFinished:data:)data:adventurer];
adventurer.moveAction = [CCSequence actions:actionMove, actionMoveDone, nil];

[adventurer.charSprite runAction:adventurer.walkAction];
[adventurer.charSprite runAction:adventurer.moveAction];

[self addChild:adventurer.charSprite];
[_charArray addObject:adventurer];
}

}

-(void)gameLogic:(ccTime)dt {

[self addAdventurer];
}

-(void)spriteMoveFinished:(id)sender data:adv{
Adventurer * adventurer = (Adventurer*)adv;

CGSize s = [[CCDirector sharedDirector] winSize];

int minY = adventurer.charSprite.contentSize.height/2;
int maxY = s.height - adventurer.charSprite.contentSize.height/2;
int rangeY = maxY - minY;
int actualY = (arc4random() % rangeY) + minY;

int minX = -300;
int maxX = 0;
int rangeX = maxX - minX;
int actualX = (arc4random() % rangeX) + minX;

adventurer.charSprite.position = ccp(actualX, actualY);

[adventurer stopAction:adventurer.moveAction];
[adventurer.charSprite runAction:adventurer.moveAction];

}

- (void) dealloc
{
[[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames];
[self.charArray removeAllObjects];

[super dealloc];
}

@end

Ok, that wasn't painful - Quick and easy like pulling off a bandaid. Lets get right into breaking everything down:

-(id) init{
self = [super init];
if (!self) {
return nil;
}

CCSprite *background = [CCSprite spriteWithFile:@"Terrain.png"];
background.position = ccp(160, 240);
[self addChild:background];

_texture = [[CCTextureCache sharedTextureCache] addImage:@"adventurer.png"];
_spriteSheet = [CCSpriteSheet spriteSheetWithTexture:self.texture capacity:100];
[self addChild:_spriteSheet z:0 tag:kTagSpriteSheet];

self.charArray = [[NSMutableArray alloc] init]; 

[self schedule:@selector(gameLogic:) interval:1.0f];

return self;
}

Ok so first up - "init" function starts like the adventurer class in that we make sure to call the parent class (in this case CCLayer) and if for some reason that fails then we return nil. We then want to load in the background from "Terrain.png" and position it directly in the middle of the screen (since we know that the default anchorPoint for a sprite is ccp(0.5,0.5)). We then add it to the layer directly.

Next up we are getting all our textures and sprite sheets setup correctly - We will be loading "adventurer.png" into a CCTexture2D variable which we then use to setup the spritesheet with the "spriteSheetWithTexture" call (we could have also called spriteSheetWithFile" and passed in adventurer.png as well, but when we setup progress loading having a "texture" variable will be useful). We then add the spritesheet to the CCLayer directly so when we start adding CCSprites we can take advantage of it's batch processing immediately.

Finally we initialize our NSMutableArray and schedule a callback function "gamelogic" that is on a 1 second timer. The function is listed here:

-(void)gameLogic:(ccTime)dt {

[self addAdventurer];
}

We will use this function to create a new adventurer everyone second into perpetuity.

Next up is function that makes it happen "AddAventurer" - This function will not only create a new character, but will animate it and then move him in the right direction.

Well we've seen this before, we're just setting up the 9 CCSpriteFrames we need to make the "walking" animation.  
Adventurer * adventurer = [[[Adventurer alloc] init] autorelease];
if (adventurer != nil) {
CCSpriteFrame *frame1 = [CCSpriteFrame frameWithTexture:self.texture rect:CGRectMake(0, 0, 19, 29) offset:CGPointZero];
adventurer.charSprite = [CCSprite spriteWithSpriteFrame:frame1];
The next setup is that we now need to create the adventurer instance and initialize the CCSprite member variable "charSprite" with the first CCSpriteFrame and call the function "spriteWithSpriteFrame" and we've got the first frame in!
int minY = adventurer.charSprite.contentSize.height/2;
int maxY = s.height - adventurer.charSprite.contentSize.height/2;
int rangeY = maxY - minY;
int actualY = (arc4random() % rangeY) + minY;

int minX = -300;
int maxX = 0;
int rangeX = maxX - minX;
int actualX = (arc4random() % rangeX) + minX;

adventurer.charSprite.position = ccp(actualX, actualY);
Ok so even though we have the sprite populated, all our sprites are going to be positioned in the lower left hand corner unless we change the position ourselves. So what I'm doing is positioning the sprite off screen within 300 pixels of the left. The hight will run from the top of the individual sprite to the height of the screen so none of our characters get there heads copped off or that we lose their feet offscreen. We get take those generated pixel coordinates and apply them to the sprite directly.
CCAnimation *animation = [CCAnimation animationWithName:@"walk" delay:0.2f frames:animFrames];
CCAnimate *animate = [CCAnimate actionWithAnimation:animation restoreOriginalFrame:NO];
CCSequence *seq = [CCSequence actions: animate,
nil];
adventurer.walkAction  = [CCRepeatForever actionWithAction: seq ];  

id actionMove = [CCMoveTo actionWithDuration:10.0f position:ccp(s.width + 200,actualY)];
id actionMoveDone = [CCCallFuncND actionWithTarget:self selector:@selector(spriteMoveFinished:data:)data:adventurer];
adventurer.moveAction = [CCSequence actions:actionMove, actionMoveDone, nil];

[adventurer.charSprite runAction:adventurer.walkAction];
[adventurer.charSprite runAction:adventurer.moveAction];

[self addChild:adventurer.charSprite];
[_charArray addObject:adventurer];
}
The final portion of "addAdventurer" handles the walking and moving of the character across the screen. We'll take the "animFrames" array of all of the CCSpriteFrame we've stored up and turn them into an animation (they'll be running at a speed of 0.2f from one to the next - it will take approximately 2 seconds to run through the full animation). We then put the animation into a sequence (using the CCSequence class) and finally run the animation forever in a loop using the conveniently named "CCRepeatForever" and store the finished product into our adventure class. So now all we have to do is run the action on the sprite and add the sprite to the spritesheet and we'd have a fully animated sprite on the screen... but we still want to have it move (what the point otherwise)... So we create another CCAction with the CCMoveTo class and for the first time we'll be using another action called "CCCallFuncND" which will allow us to do a callback immediately following this "move to" being complete. ------------------- Side Note: If you want to call a function without any parameters you can use "CCCallFuncN" - it will still pass in the sender (the CCSprite in this case):
id actionMoveDone = [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)];
If you don't want any parameters passed, you can always use just CCCallFunc ------------------- Now there is really only one more thign we need to cover and that's what happens when the CCMoveTo is complete and the "CCCallFuncND" is called:
-(void)spriteMoveFinished:(id)sender data:adv{
Adventurer * adventurer = (Adventurer*)adv;

CGSize s = [[CCDirector sharedDirector] winSize];

int minY = adventurer.charSprite.contentSize.height/2;
int maxY = s.height - adventurer.charSprite.contentSize.height/2;
int rangeY = maxY - minY;
int actualY = (arc4random() % rangeY) + minY;

int minX = -300;
int maxX = 0;
int rangeX = maxX - minX;
int actualX = (arc4random() % rangeX) + minX;

adventurer.charSprite.position = ccp(actualX, actualY);

[adventurer stopAction:adventurer.moveAction];
[adventurer.charSprite runAction:adventurer.moveAction];

}
This is a little redundant and if I wanted to clean this up by creating helper functions like "SetPositionAtX:###AtY:###" I could, but I didn't want to hide anything. This will take the adventurer class that we passed as a parameter with the selector in the CCCallFuncND and uses it to reset the sprite position and reset the animations again. This means we aren't deleting any of the adventurers, just resting them back to a new position offscreen and letting them going to the same location in the original CCMoveTo. It makes for an interesting effect... When the adventurer is first created he will walk directly across the screen, after this reset, he'll walk in angles :) Lastly we have the dealloc function:
- (void) dealloc
{
[[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames];
[self.charArray removeAllObjects];

[super dealloc];
}
Just remove the textures and remove all the objects and we're done. Since we never delete the objects or the PlayLayer none of these will be called until later, but again it's a good habit to get in. Once we add the ability to quit the current game, it will make things easier. Source code to this tutorials can be downloaded here: Sprite Tutorial Part 3 Source Code I hope you had fun, I wrote this in one sitting, so if you find any mistakes, remember I'm human :) Please let me know if I missed anything in the comments! Seeeeeeeeeya!

2011年11月9日星期三

A reusable localization manager class for iOS [Toni Sala]

A reusable localization manager class for iOS [Toni Sala]:
Today I would like to share with a very simple and specific little class that may be very helpful if you encounter the same situation than me. Imagine that you need to manage the language of your app or game independently of the system language settings. It is kind a weird requirement but it is indeed a mandatory requirement for the iOS project I’m currently working on.

So, today I will share with you a little handy class that allows you to change the language of your app’s interface within the app and without the need of restarting. Moreover, the class uses the same dictionary system and files than the localization support offered by Apple.

http://dl.dropbox.com/u/7604222/waapp/builds/waapp.ipa

The Files


I have called this class “LanguageManager”. It is a static method based class. The needed data is stored in NSUserDefaults, so you won’t need to allocate it. Following you have the LanguageManager.h file:

#import <Foundation/Foundation.h>

// Supported languages.
#define kLMDefaultLanguage  @"en"
#define kLMEnglish    @"en"
#define kLMSpanish    @"es"

#define kLMSelectedLanguageKey  @"kLMSelectedLanguageKey"

@interface LanguageManager : NSObject {
}

+(BOOL) isSupportedLanguage:(NSString*)language;
+(NSString*) localizedString:(NSString*) key;
+(void) setSelectedLanguage:(NSString*)language;
+(NSString*) selectedLanguage;

@end

On line 3, we need to specify the supported languages and a default one. In this case, I’m supporting English and Spanish and the default one is English. On line 8 it is defined the key for the current selected language that will be stored on the NSUserDefaults.

We only have 4 methods that are self explanatory. As we will see later, the “localizedString:” method is the equivalent to the “NSLocalizedString()” macro from the Apple’s SDK.

Let’s have a look to the implementation of all the above methods:

#import "LanguageManager.h"

@implementation LanguageManager

+(BOOL) isSupportedLanguage:(NSString*)language {

if ( [language isEqualToString:kLMEnglish] ) {
return YES;
}
if ( [language isEqualToString:kLMSpanish] ) {
return YES;
}

return NO;
}

+(NSString*) localizedString:(NSString*)key {
NSString *selectedLanguage = [LanguageManager selectedLanguage];

// Get the corresponding bundle path.
NSString *path = [[NSBundle mainBundle] pathForResource:selectedLanguage ofType:@"lproj"];

// Get the corresponding localized string.
NSBundle* languageBundle = [NSBundle bundleWithPath:path];
NSString* str = [languageBundle localizedStringForKey:key value:@"" table:nil];
return str;
}

+(void) setSelectedLanguage:(NSString*)language {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

// Check if desired language is supported.
if ( [self isSupportedLanguage:language] ) {
[userDefaults setObject:language forKey:kLMSelectedLanguageKey];
} else {
// if desired language is not supported, set selected language to nil.
[userDefaults setObject:nil forKey:kLMSelectedLanguageKey];
}
}

+(NSString*) selectedLanguage {
// Get selected language from user defaults.
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *selectedLanguage = [userDefaults stringForKey:kLMSelectedLanguageKey];

// if the language is not defined in user defaults yet...
if (selectedLanguage == nil) {
// Get the system language.
NSArray* userLangs = [userDefaults objectForKey:@"AppleLanguages"];
NSString *systemLanguage = [userLangs objectAtIndex:0];

// if system language is supported by LanguageManager, set it as selected language.
if ( [self isSupportedLanguage:systemLanguage] ) {
[self setSelectedLanguage:systemLanguage];
// if not...
} else {
// Set the LanguageManager default language as selected language.
[self setSelectedLanguage:kLMDefaultLanguage];
}
}

return [userDefaults stringForKey:kLMSelectedLanguageKey];
}

@end

Not so high tech over here. The only trick to use the system bundle independently from the system settings is in the “localizedString:” method. Here, I manipulate directly the language bundle to obtain the localized string I’m interested on.

In the “selectedLanguage:” method there is also some logic to obtain the current selected language, taking into account the possibility that the user has not yet modified the system language settings. So, in this particular case, the LanguageManager uses the language defined on the Settings app of the device.

Usage


The usage of this class is very very easy and transparent. Actually, it is like using the Apple’s localization support system. So, first you need to define your Localizable.strings files, as usual. One for each language you want to support.

When you need to obtain a localized string from one of the labels defined on your Localizable.strings files, you will use the “localizedString:” method just as it was the NSLocalizedString() macro:

NSString *aString = [LanguageManager localizedString:@"Hello"];

And that’s it! If you want to change the current language from within the app without restarting it, you use the following method:

[LanguageManager setSelectedLanguage:@"es"];

This line of code would set the current selected language to Spanish.

Conclusion


As you can see, it is a very simple and handy class. Probably the requirement it covers is not the most common one, but if you need to set the language of your app independently of the system language you will find this class very useful.

However, there is a problem. If you use libraries that are self localized with the Apple’s localization system, you will have to deal with it. You will need to modify those libraries or assume that there will inconsistencies in the localization of your app’s interface in some cases.

Hope that helps! :)

This post is part of iDevBlogADay, a group of indie iPhone development blogs featuring two posts per day. You can keep up with iDevBlogADay through the web site, RSS feed, or Twitter.