Archive for 'Programming'

Tutorial: JSON over HTTP

We’ve mentioned the json-framework project before; but here’s an excellent tutorial on how exactly to use it that you really should not miss if that’s something you need to do.

Also note this other alternative, ObjectiveResource, which handles both XML and JSON deserialization in the context of interacting with Ruby on Rails applications, a port of Ruby’s ActiveResource apparently…

h/t: iPhoneKicks!

Continue Reading →
0

Snippet: Singletons

So there was this thread about using the Singleton pattern, and it went right quick into the usual whining about it being an anti-pattern and all, but there were a couple interesting links that turned up:

Singletons, AppDelegates and top-level Data is a good Cocoa-centric overview of the topic, and we direct your attention particularly to the SynthesizeSingleton.h header provided, which macroizes all the support you’d need if you wanted to use a singleton with conventional allocation semantics. Which strikes us as unlikely, but hey.

The interesting part though is the allocation question. The above-linked file relies on the @synchronized directive in allocation, which we think is a little unwieldy, as well as being Objective-C 2.0 dependent. So how to ensure thread safety then? Interesting discussions here, and here, and here, and here; that OSAtomicCompareAndSwapPtrBarrier idea strikes us as particularly nifty.

But here’s our idiom for setting up singletons; just do it at static initialization time, like this for initializing application settings:

static PMPESettings* _sSharedSettings = [PMPESettings sharedSettings];
@implementation PMPESettings


+ (void)initialize
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
[[self sharedSettings] load];
[pool release];
}


+ (PMPESettings *)sharedSettings
{
if (!_sSharedSettings)
_sSharedSettings = [[self alloc] init];
return _sSharedSettings;
}


- (void)load
{
... if there aren't any saved settings, fill in defaults...
}

@end

So long as we’re not doing ridiculous things at static initialization time — and oh boy, have we got some stories we could tell you about things we had to port that were completely dependent on Visual Studio’s link order! — but just sorting things into usable states, like above where -load creates default application preference values when none exist, this seems to me to be a perfectly reasonable way to leverage compiler and Objective-C semantics to sidestep synchronization worries completely. What do you all think?

h/t: iPhoneSDK!

UPDATES:

And if you want to read lots of advice on singleton implementation…

Ship-It Saturday: PRHEmptySingleton repository

Objective-C Singleton Class Template

Everyone has a singleton, and this is mine

How I do my singletons

Require OS 4? Hey, guaranteed alloc safety: Singletons: You’re doing them wrong

This looks like pretty much the final, universally compatible, word on the subject: Objective-C Singleton

Continue Reading →
0

Tips: Localization

Heh. This fellow with, apparently, way too much time on his hands went digging around in AppKit and found out that there’s an undocumented call _NXKitString that lets you cheat on your localizations by accessing AppKit.framework’s tables directly.

Now, we really really don’t recommend you ever ship anything using that, but it is interesting to note the source of these tables:

To see what’s there, navigate to the following location:

/System/Library/Frameworks/AppKit.framework/Versions/C/Resources/

From there, you can navigate into the English.lproj directory, for example, where you’ll see a list of string table files, all of which have the suffix “strings”. These represent the allowable table names that you pass to _NXKitString. So, “Preferences” maps to Preferences.strings and so on.

So not only can you save yourself some pennies on your own translation costs by digging through there, far more importantly, for any particular string that happens to be there, you can get The Official Apple-Approved translation … as opposed to the real howlers completely inconsistent with the rest of the system that your commissioned translators have a way of throwing at you, one finds on occasion. Because they always claim yes we are completely familiar with Apple conventions in all the languages you want … but that does not always turn out to indeed be the case.

While we’re discussing localization, if you have 23 localizations to spit out RIGHT NOW! like some of us do, here is a new addition to our Invaluable Development Tools list, LangSwitch:

The only boring and time-consuming solution is to thoroughly test the new UI in every localization before releasing. This is especially time-consuming as you have to change the language settings in System Preferences every time you want to change the localization.

Also, another downside of this is that it changes your whole computer (well, just your session, but whatever…). I personally don’t really like to use a computer in Chinese…

That’s where LangSwitch comes in… It gives you a simple GUI way to switch the localization for only the app you’re testing. It displays only the localizations avaiable for your app. Here’s an easy way to test your different localizations without the hassle.

Is that sweet, or what? Works just as described, and somehow manages to maintain the designated localization even after an Xcode Clean All and rebuild. Not completely sure just how it’s managing that, but it’s certainly a useful trick!

And here’s a useful little tip for the use of genstrings if you like, as we do, to organize your source in folders; this command will recurse two levels down your hierarchy to pull out all your source strings:

genstrings *[hmc] */*[hmc] */*/*[hmc]

To finish off, here’s a few other recent useful posts regarding localization you may wish to also read over if this happens to be a concern of yours at the moment:

ibtool: Localization Made Easier

Localizing iPhone Apps – Internationalization

Cocoa Localization Guide

[EDIT: And here is a web service that might be worth your looking into!]

Continue Reading →
5

Snippet: Orientation

Here’s a useful post on dealing with interface orientation changes:

One of the features with which I had to get fairly intimate with on the iPhone over the last couple of months was working with orientation changes. At first my code was completely incorrect and it wasn’t immediately obvious to me how to get my application to reorient itself properly. This was mainly due to the structure of my code. In this post I am going to explain a simple, memory efficient way of working with UIViewController and interface orientation changes.

We draw your attention particularly to the ‘Pitfalls’ discussion:

… I did have an issue where I was using 3 view controllers. Let’s call them A, B and C. A switched to B and vice-versa when the phone’s orientation changed. C was loaded by B and was viewable in landscape and portrait orientations. The problem came in where if you changed C’s orientation and then the user navigated back to B where B had a different orientation, you would effectively not be notified of an orientation change. If you subsequently changed B’s orientation to load A, you would find A would load in the wrong orientation. Oops, bug…

So how did I solve this? Well all I did was put this piece of code in A so that it would manually reorient itself from portrait to landscape:

- (void)viewDidAppear:(BOOL)animated {
	if(UIInterfaceOrientationIsLandscape(self.interfaceOrientation)){
		[UIView beginAnimations:@”View Flip” context:nil];
		[UIView setAnimationDuration:0.5f];
		[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
		self.view.transform = CGAffineTransformIdentity;
		self.view.transform = 
			CGAffineTransformMakeRotation(MPI * (90) / 180.0);
		self.view.bounds = CGRectMake(0.0f, 0.0f, 480.0f, 320.0f);
		self.view.center = CGPointMake(160.0f, 240.0f);
		[UIView commitAnimations];
	}
}

That’s a handy little snippet to keep in mind, indeed.

h/t: iPhoneSDK!

Continue Reading →
0

Tools: Shark

So if you’ve been doing Mac programming for a while, you’re probably aware that Shark is a tool of veritably godlike omniscience when it comes to profiling your application and finding out just what it is that needs optimization. But were you aware that you can do on-iPhone application profiling with it as well? 

Well, maybe you were, but we weren’t. And if you weren’t either, here’s how you do it to get all the source codey goodness of Shark handily:

1) Run your application from within Xcode on the device.

2) Start up Shark (/Developer/Applications/Performance Tools/ is where it lives).

3) Select “Network/iPhone Profiling…” from the Sampling menu.

4) Sort out the resulting dialog as explained here so it looks like this:

shark

Note that this demonstrates Vital Tip #1: Select the particular process of interest, do NOT leave ‘Target’ atthe default of ‘Everything’. We tried that at first, since hey it’d be neat to see the complete list of what’s going on, logged for about 40 seconds … and eleven hours later, it was still chugging away with “Shared devices processing samples” without even having figured out how much work there was to do to get the progress bar started. Yeah, alright then, we won’t do that, will we.

After sorting that out, it’s a matter of a few minutes to get what looks like all the same information from your iPhone app that you can for your desktop apps. It’s amazing what you can find if you just think to actually look, isn’t it now?

Continue Reading →
0

UIWebView tips

Here’s a useful collection of tips on using UIWebView:

- Loading the SVG file from your resources folder
- UIWebView loading contents when it is off-screen
- Calling a javascript function from Objective-C
- Javascript communicating back with Objective-C code
- Disabling the selection flash
- Disabling the “action” pop-up
- Disabling default zoom effect

Something there for everybody. And here’s one more:

Common problem, need to apply nice HTML formatting for a section of your page, but want the UIWebView not to appear as a big white box – only the content of the UIWebView to appear. How to do it?

myWebView.opaque = NO;
myWebView.backgroundColor = [UIColor clearColor];
[myWebView loadHTMLString:
@"<html><body style='background-color: transparent'>
       Content Here</body></html>" baseURL:nil];

Now you know!

Continue Reading →
0

Code: Reachability

Whoops, here’s something we’d overlooked in our latest app effort — good thing we stumbled across this before submitting it! — if your application is network dependent, apparently Apple requires that you detect network availability proactively, spinning helplessly in its absence is not sufficient. From this top 11 list of rejection reasons:

6. Popup for network detection If your app requires the use of the Internet, you must detect when the network is unavailable and provide a pop-up message informing the user. Just having the spinning busy icon display and a message saying “trying to connect” is not sufficient. Apple will reject your app if you don’t provide a message informing the user that they need a network connection.

Ah, OK then. No worries, we’ll just grab the Reachability sample … wait, what?

7. False claims of a missing network On a related note, make sure you don’t have any false positives in your network detection. There’s a bug in the “reachability” functions provided by Apple. If you don’t first try to perform a network connection but instead just do a reachability test, the code will always report the network is unavailable. Apple will reject your app if they discover you have this false positive case.

Actually, it looks like what I presume is the “bug” referred to above in Reachability is indeed not such … not exactly, anyways. The trick is, you want your first status check of your target host name’s reachability to be made synchronously. Because, until it completes the check, well, it’s not connected, is it now? Quite logical, really. And once that initial check is sorted, then your updates should properly be asynchronous. So in Reachability’s appDelegate where it has

[[Reachability sharedReachability] setHostName:[self hostName]];
// The Reachability class is capable of notifying your application when the network
// status changes. By default, those notifications are not enabled.
// Uncomment the following line to enable them:
//[[Reachability sharedReachability] setNetworkStatusNotificationsEnabled:YES];
...
[self updateStatus];

that’ll always return false for your target host reachability in -updateStatus if you follow the given instructions. Whoops! To fix that, simply do a synchronous then an asynchronous query

[[Reachability sharedReachability] setHostName:[self hostName]];
[self updateStatus];
[[Reachability sharedReachability] setNetworkStatusNotificationsEnabled:YES];
[self updateStatus];

… and you’re all good.

It would be more clear that the first host reachability check failing was a foreseeable occurrence if -setNetworkStatusNotificationsEnabled was actually labelled -setStatusResultsAsynchronous. Or, even better,
-callThisToMakeTheSampleFailHaHaSucka. But Apple very rarely labels sample code quite that honestly!

Continue Reading →
7

Testing: Squish!

Something to keep your eye on here: An upcoming GUI testing tool for your Cocoa Touch applications! Yep, the most deliciously named froglogic is promising a version of their Squish testing tool by “the upcoming Squish 4.0 release”, whenever that is.

Squish is a professional, cross-platform GUI and regression testing tool that enables testers to create and execute automated GUI tests for applications based on a variety of different GUI technologies. This includes applications based on Nokia’s Qt, Mac OS X Carbon and Cocoa, Java SWT/Eclipse RCP, Java AWT/Swing, Web/HTML/AJAX, and many other UI technologies. Squish stands out from other GUI test tools thanks to its close integration with each supported GUI technology—a feature which helps ensure that tests created with Squish are very robust and stable.

That’s quite the feature set, isn’t it now. Any of our Gentle Readers have any experience with Squish on this plethora of other platforms and have an opinion of how exciting this news actually is?

h/t: Jeff!

Continue Reading →
0

Code: L0SolicitReview

Well, this is an innovative approach to the problem of getting good reviews on the App Store: just go ahead and ask for them!

We all agree that having JUST negative solicitation (that is, Apple’s rate-on-delete) is bad, whether we agree or not that having it is a good thing (I think it is). What we lack is a way to solicit positive reviews from satisfied users to counteract the rate-on-delete ratings slump.

Well, here it is:

Find it on Google Code as part of the author’s UIKitPlus project; dunno if it will actually help with the negative selection problem … but it very likely isn’t going to hurt. One can hope.

h/t: iPhoneSDK!

UPDATE:

Here’s another class for the prompt for reviews and ratings kind of thing:

Presenting, Appirater

Continue Reading →
1

Code: SCListener

Here’s a good start for you if you’re interested in putting some microphone-activated features into your iPhone app:

Voice activation. Sounds cool, doesn’t it? And all the cool people are using it! Nintendo was on to something with their DS and its microphone: Wario’s little games were no match for a little heavy breathing. With the iPhone, Smule is using it up a storm! And iSteam? Yes! These guys get it: people love doing stuff with their mouths! If there’s some kind of reward involved, well then, now you’re talking. Blowing out candles, kissing, outright yelling up a scene—these are the things of life, right?

Yes, indeed. We’ll just lightly skip past that mouths bit, for the sake of our gentler readers, and focus on the code: it’s called SCListener and it’s on github for you to download. That’ll get you the input set up and metered … and off to the races with your blowing application. Er, we mean the application that you blow … er, no, we mean … yeah, well, you know.

Continue Reading →
0
Page 78 of 93 «...5060707677787980...»