Showing posts with label iphone. Show all posts
Showing posts with label iphone. Show all posts

Tuesday, April 20, 2010

UIPageControl - let's customize !

Over on AppTech I have posted a small article about how to customize a UIPageControl so that it can be used on a white background.

UIPageControl provides a view similar to the white dots on your iPhone's home screen for use within an app. As you might know, it only displays the dots in white so it's virtually unusable on a white background. Hop over to AppTech to discover how you can customize UIPageControl and leave a comment!

Monday, March 8, 2010

Network Availability and Transparent OpenGL

Two more blog posts are online on http://apptech.next-munich.com.

The first post goes into details on how to use the Reachability class provided by Apple to detect network availability on iPhone and iPod touch.

The second post describes my first dive into augmented reality apps. In this particular case I give some information on how to integrate an OpenGL view managed by cocos2d with the UIImagePickerController. It details where you have to modify cocos2d code to make the OpenGL view transparent - which is a requirement in case you want to overlay the camera image with the OpenGL view.

Wednesday, February 10, 2010

Audio Recording

Quick post on audio recording in iPhone apps on App Tech:

Tuesday, January 19, 2010

Invalid SSL certificates

Just posted a small piece on ignoring invalid SSL certificates within an iPhone App. Be sure to head over to http://apptech.next-munich.com to read the article.

Monday, January 4, 2010

symbolicatecrash

For the first post in 2010, I have decided to write a small piece on Apple's symbolicatecrash tool. Head over to http://apptech.next-munich.com to read about my findings.

Saturday, December 12, 2009

Background Music & SFX on iPhone

I'm so glad that many people are sharing their findings and how they are getting things done in iPhone:

First of all, there is a super-convenient set of classes in the cocos2d package that can be used for playing background music and sound FX. The only thing I have to figure out is how I can tweak these guys to stop iPod music in case the user explicitly wants to enable in-game sound. But that's probably a piece of cake, too!

The next help comes from Tinker Blog which lists suitable file formats and conversion commands. Essentially, iPhone allows you to play one compressed file (like MP3) and several uncompressed files in parallel. Since there's only a single hardware decoder for compressed files available, not more than a single compressed file can play at the same time, though. The idea is to take your most expoensive sound and use it as an MP3 within your application (eg background music) and convert the smaller sounds (typically sound effects) to a format like "IMA4" packed inside of a "CAF" file.

Thursday, December 3, 2009

Leak Hunting in iPhone Code

Eventually, when you're closing in on the release candidate of the software you're working on, you're probably going to check your app for memory and performance issues.

Same for me. On my current iPhone project, we're getting closer to our first beta and I felt I had neglected checking my memory usage and whether there are any apparent memory leaks in my app. Firing up Instruments, Apple's tool for analyzing Mac and iPhone software in many different ways (Memory, Disk Access, Open GL, Leaks, Core Data to name just a few), I was pretty happy with what I saw: the Leak-Detection tool did only find a couple of minor places in the code where I was leaking memory.

The output of Instruments, though not very intuitive at first, helped me identify the places in my code where I was allocating and / or retaining objects which I never released when it was time for them to be released. After patching those holes only a couple of leaking places were left that did not trace back into application code but into system APIs. Good job, I thought.

Coming from a Java background where I never had to spent a lot of thoughts to memory management (unless, of course, the occasional image = null; System.gc(); calls), switching to a reference-counted environment on the iPhone seemed to easy to be true. And sure enough I was going to find out that things are slightly more involved than checking the Leak tool in Instruments!

My colleague discovered the issue when he kept playing the game for longer than I had ever done. At some point in time, loading one of the included mini games, the application just crashed. Memory was his first thought and I also felt like it was some problem with running out of memory. Fortunately I was able to reproduce the bug and could see memory usage increase in Instruments while navigating the game.

After some time of digging for an answer I discovered an issue that was not detected by the Leak tool: cyclical references. Here I retained an object representing my scene for it to render properly while active. Within that object I created another object, however, which was retaining the scene. Once the scene was removed from screen, deallocation did not take place since the retain count of the scene did not reach 0.

How did I catch that one? A good indicator is ever increasing memory usage within your application. Monitor that while running on the phone itself to get a more accurate picture of your memory's distribution between Open GL ES memory and "regular" memory. I tried to explicitly free all my textures by calling cocos2d's [[TextureMgr sharedTextureMgr] removeAllTextures] method. Since this did not free any Open GL memory at all, something was going on. Finally, I carefully tracked memory usage using the Memory instrument when taking well-defined steps within the app. Once I had discovered a point where memory did not go back to where it was supposed to be (in case all of the memory had been free'd), I added some logging to see whether the object's I wanted to be dealloc'ed really were disposed of. That step let to the discovery of the the leak - maybe this will help you find some in your code, too!

Here's some sample implementation code to highlight what was happening:



This code kind of looks ok at first but soon you'll notice, that MyScene is never going to be dealloc'ed unless you explicitly call its' release selector twice somewhere outside of this code (which is going to lead to other problems - so don't do this!).

Assume the following code to understand why this is happening:



As you will probably know from Apple's documentation, whenever you're using alloc / init to create an instance of a class, you've implicitly retained the object. You have to explicitly release the object to properly dispose of the object. Now pay attention to the object's retain count:

1. The call to [[MyScene alloc] init] gives you an implicit retain count of 1.
2. Additionally, MyObject retains the allocated scene thus increasing its' retain count to 2.
3. Once [scene release] is called, the retain count is reduced to 1.

As you can see, the retain count is not going down to 0 as it should because of the retain by MyObject. Since MyObject only releases its' reference to MyScene in dealloc, this is not going to happen unless you explicitly send the MyObject instance the release selector.

The easy fix: if MyObject only lives as long as the scene is living, just don't retain the scene. It's going to be alive as long as MyObject is alive so there is not going to be a problem.

If you think this is happening to you, too, make sure you log the retain count of the object in question at appropriate times (whenever you think this object should be dealloc'ed but isn't). You can do this with a single line of code:



Hope this helps you find the pesky cyclical memory leaks. When is there going to be an app for that, too?

Did you find any other common patterns of leaks that are not detected by Instruments? Share your findings in the comments! I'm surely going to be thankful but so are probably all the other readers / Google users.

Wednesday, November 25, 2009

The Quest to implement a custom Text Field

To match the UI of the App I'm working on right now, I needed a text field with a custom look and feel that would nicely integrate with cocos2d.

I thought there must've been someone out there who has already accomplished / implemented something like this but after a while of google'ing and browing the cocos2d forums, I figured that there seems to be no final, working source code of something like this available.

With some help from this post by Jack and David (and some other stuff I don't seem to be able to remember), I eventually managed to code something myself which combines the rendering abilities of cocos2d (Sprites and BitmapFontAtlas) with the input capabilities of UITextField. This sure feels like a hack as I'm using an "invisible" (read: very tiny) UITextField to handle the text input while rendering the intercepted text using BitmapFontAtlas and some other Sprites but - hey - it works just fine.

I'll check with the people at cocos2d whether it would be worthwhile to include such a class in the main distribution. In the meantime, the files are available here.

Here's how you'd use the TextField class in your own projects:



Hope this gets you going much quicker than me! Now enjoy the code and let me know what you think!

Thursday, November 12, 2009

Enhanced Fonts in cocos2d

One thing I came across in cocos2d was an issue with the font rendering. Since the fonts produced by Hiero bitmap font editor are very tightly packed on their containing images, rendering artefacts can appear when cocos2d displays the characters on screen.

Several people have reported these issues but I did not find a solution that fixes the problem in all cases. For that reason I have slightly amended the Hiero bitmap font editor: the modified editor outputs the fonts with more space between individual characters and amending the characters rectangles in the font definition files. This works very well and fixes the issue for me. I'll try to get in touch with Hiero's maintainer (who seems to be this guy) and will check whether there is any chance of having this feature integrated into the official version of the editor.

Another thing relating to fonts is the calculation of a string's width and, based on these calculations, a proper algorithm for line and page breaking. As I did not find such a facility within cocos2d source code, I enhanced the BitmapFontAtlas class to provide all of these. Basically, before calling [label setString:@""] to set the text for a label, you can assign a size to the label using

label.size = CGSizeMake(width, height);

If such a size has been assigned, a call to

[label setString:@"A very long string with reeeeeaaaaalllllllyyyyyyyyyyyyyyyyyyy long words and\nforced line breaks."];

will split the string according to the given size. The string will first be divided into lines (obeying the maximum width assigned earlier), then into pages (additionally obeying the maximum height). The first page will then be used as the string displayed by the label.

To choose a different page and figure out the amount of pages available within the label, you can then use the properties label.currentPage and label.pages respectively. If you assume that you want to switch to page 1 and this is within the amount of pages available, you can just assign label.page = 1 and be done.

If you don't assign a size before your call to [label setString:@""], the text is going to be rendered as with the unmodified version of BitmapFontAtlas. The only added benefit is that forced line-breaks using @"\n" are supported.

For this change, too, I'll try to contribute back to the cocos2d project. I will keep you updated!

Friday, October 30, 2009

Running Actions in cocos2d during onEnter

I just discovered a requirement in the onEnter method when you try to run a duration-based Action in cocos2d. Whenever you're trying to do something like this within the onEnter method of a subclass of Layer:

[node runAction:[FadeIn actionWithDuration:1]];

make sure you call the super class' onEnter method. Otherwise the action will not perform what you try to achieve. Working code looks like this:



Hope this helps someone and saves some time!

Sunday, October 18, 2009

iPhone and Unit Tests

Finally, following a series of posts on Luis de la Rosa's blog, I have Google Toolbox for Mac up and running my Unit Tests for iPhone.

Here's a quick note in case you choose to download the latest code from SVN instead of downloading the pre-packaged v1.5.1 from Luis' page: in addition to the files he copies to the sample project, you need to copy two additional files, "GTMObjC2Runtime.h" and "GTMObjC2Runtime.m", into your "UnitTestFramework" group within Xcode. With these files included, your build of the UnitTest target will work successfully.

Now having a look at the continuous integration suggestions by Michael Nachbaur. Let's see whether I can get a Hudson instance running and packaging both, my test targets and the final application.

Thursday, October 15, 2009

Automatic version numbering in Xcode

Here's a nice piece on automatic version numbering from within Xcode. The article details almost all the work you have to perform to get automatic versioning up and running.

Here are the missing pieces:
  1. Place the Xcode config file in the root of your project.
  2. In your Info.plist file change the value for "Bundle version" to something like "0.1 (${CURRENT_PROJECT_VERSION})" - depending on your choice for the variable in the config file.
With those two things in place, versioning should be up and running in no time. Thanks, Diego!

Wednesday, October 7, 2009

Properties vs Instance variables

So being able to work with properties in Objective-C is very nice but there are subtle things to keep in mind when using them.

I just came across a problem which cost me about 30 mins of my time. In one of my methods I was (supposedly) assigning an object to one of my properties. The property was marked with retain so that it was supposed to be retained unless re-assigned or the owning object is dealloc'ed. Unfortunately, in a different part of the code, accessing that very property threw an exception.

Turns out that I hadn't yet mastered the subtle difference between properties and instance variable. Assume the following code sample:

@interface Foo : NSObject {
NSString* bar;
}
@property (retain) NSString* bar;
- (void) test;
@end

@implementation Foo {
@synthesize bar;

- (void) test {
NSString* str = @"Test";

// this assignment does not use the synthesized setter
// but accesses the instance variable directly
bar = str;

// same here
self->bar = str;

// only this way of accessing uses the setter and thus
// retains the object reference
self.bar = str;
}
}

First of all I did not know about the arrow-way of accessing instance variables, secondly I thought access as displayed in the first assignment would use the setter method.

Hope this helps in case you're ever going to scratch your head because of this!

genstrings / copystrings

Setting up an iPhone project I came across some weird behviour with genstrings / copystrings commands.

In principle, genstrings is responsible for searching your source code for macro statements of the form NSLocalizedString(@"keyword", @"description") and will place an entry in a (UTF-16) text file called Localized.strings for each macro it discovers.

Now if you use this command to generate the file, add it to your project, localize it (by Right-clicking on the file, choosing "Get Info" and "Make Localizable") everything works great. If, however, you create that file manually (in my case using TextWrangler) the copystrings command will fail during the build process. I'm quite sure that this is somehow related to file permissions on Mac OS X but couldn't quite figure out what was going wrong. After all, the file permissions that you could see in Finder were the same either way.

If anybody else came across this and solved it (got manual creation of that file to work), let me know!

Thursday, October 1, 2009

iPhone drawing

I'm not sure whether I just got bad at googling things but apparently, when I first researched bits and pieces about rendering stuff on iPhone, I did not find the way of rendering I was so desperately looking for:

Instead of diving into OpenGL ES right from the start, I was looking for a rendering mechanism similar to what J2ME offers: subclassing Canvas, overriding the paint() method and adding all of your drawing calls to that method.

For iPhone I expected to find a similar way of rendering and, sure enough, came across Quartz as iPhone's 2D rendering library of choice. What I did not find, however, was the part where I subclass and add the statements to a particular function in my code. Now, reading the first few lines of Dave Mark's and Jeff LaMarche's chapter on Quartz and OpenGL ES (from their book Beginning iPhone 3 Development), I finally found the missing piece:

  1. Subclass UIView
  2. Override drawRect:
  3. Add Quartz-calls

If you're wondering where you can get a handle to the Graphics context (that you'll get automatically as an argument to the method in J2ME), you use UIGraphicsGetCurrentContext() to get a handle to it.

Maybe this post looks dead-simple, I just hope some people will find it in their quest to discover the information I was looking for myself :-)

Thursday, September 3, 2009

Extending cocos2d

Today was my first real day of doing something vaguely productive using cocos2d on the iPhone.

I coded an animation creation framework (aptly called Pixel Animation Studio) some months ago which can be used to compose animations using 2d pixel graphics. Basically, an animation is broken down into frames which in turn are broken down into small fragments. This technique encourages reuse of image fragments and can save a lot of space normally wasted by duplicate content in images. I guess you can see my background as a J2ME engineer shine through ...

Anyways, to support the animations created using this tool, I need a Sprite class that can be assembled by rendering multiple images instead of a single texture. To get this working, I investigated the CocosNode, TextureNode and Sprite source code to see, how rendering is performed deep within cocos2d. Turns out it's fairly easy to do:

cocos2d already handles most of the behaviour you need for a Sprite in CocosNode. It takes care of position translations and rendering all the sub-nodes added to a CocosNode. Now you just go ahead, sub-class CocosNode and add all the images you'd like to render as children of type Sprite (or AtlasSprite). cocos2d will take care of the rest!

Since the animations produced with Pixel Animation Studio are slightly more advanced than the ones provided out of the box by cocos2d (btw, I didn't realize plain 2d, frame-based animations were supported out of the box to begin with - they are just not properly highlighted as a feature on their site), I also had to implement a new IntervalAction. That's pretty straight-forward, too: just subc-class and override the + (void) update: (ccTime) time method. When instantiating, keep in mind that cocos2d takes parameters in seconds for the actions which accept a duration parameter, not in milliseconds.

Wednesday, September 2, 2009

+ (void) load

I just happened run into one of those things that must happen to you if you just go out there and try to learn a new programming language from scratch without using any tutorial books.

Just for the sake of getting started with some Objective-C coding, I'm implementing some 2D animation functionality based on an animation tool coded in Java. Trying to load the files its creates using Objective-C, I implemented a method called load in one of my classes. Things got properly loaded - but, to my surprise, I also saw some error messages in the console hinting at leaking memory. An autorelease-pool was set up in my main class so I was wondering what could possibly have gone wrong.

Turns out + (void) load is method defined in NSObject class which is used for initializing objects. It got called even before my autorelease-pool was initialized, thus the leaking. Keep that in mind if you see error messages saying "No autorelease pool in place" or "Just leaking" even though an autorelease-pool is set up in your main class.

Sunday, July 19, 2009

cocos2d

First time really trying to get something done in iPhone SDK. After struggling ages getting a simple game loop to work - only to discover that I was calling the update routines on the wrong thread - I found a forum post which talked about the cocos2d iPhone 2D game engine.

Have now spent most of the day working on a simple Memory-like game. The engine is pretty straight forward to use once you get to know the APIs. There are a couple of things I didn't quite figure out this time, though - any insights are appreciated:

  1. Is there any reason why rendering origin in iPhone / cocos2d / OpenGL seems to be lower left corner instead of upper left? It sure matches the mathematical way of thinking about an origin but AFAIR most of the other frameworks have their origin in the upper left, don't they?
  2. To render the game board, I have assembled a Scene using a Layer and a couple of Sprites contained in that Layer where each of the Sprites was supposed to be touchable. I haven't found a way to get that working other than reacting to touches on the Layer and manually checking whether the touch fell within the bounds of one of the Sprites. There must be a better way to do this, right?
  3. How does memory management work when you replace Scenes using the Director singleton? You access the Scenes via [Scene node]; so I assume there's autorelease at work.
  4. Why do Texture2D.pixelsHigh / .pixelsWide return different values than Texture2D.contentSize?