Posts Tagged 'iPhone'

Review: Cocos2d-x by Example Beginner’s Guide

If you’ve been luxuriating in the joy of developing games iOS-centrically the last few years, it’s a pretty good bet you’ve been using cocos2d-iphone. And it’s also a pretty good bet that the pressures are mounting to acknowledge the existence of other, lesser, platforms, if you get our drift. The path of least resistance to that is to go with the cocos2d-x fork adopted as part of the cocos2d coordinated releases. But up until now there’s been a substantial dearth of documentation for that option, which the good folk at Packt have now remedied:

7341OS_cov.jpg

The first chapter runs through getting you set up and doing the Hello World thing on a Mac with Xcode with the 2.0.4 version, which is the last stable release before the book’s publication date, just in time to be superseded by the 2.1.3 release, although the differences are pretty trivial; and recommends for your tool suite that you pick up Texture Packer, Particle Designer, Glyph Designer, and cfxr. Which we’d agree with across the board.

Chapter 2 goes over the basic structure of the cocos2d framework, introduces C++ to the native iPhone developer and discusses how to live without ARC, or conversely for the C++ programmer how to live with the root class paradigm. Not sure you’d ever manage to square that circle to anyone’s complete satisfaction, but what’s here is a good attempt.

Chapters 3 through 9 go through a series of mini-game examples, introducing

  • images (including retina), sounds, sprites, multitouch, bounding collisions
  • sprite sheets, bitmap fonts, background music, actions, universal apps
  • particles, drawing primitives, vector math
  • placeholder prototyping, terrain generation, platformed collisions
  • texturing terrain, parallax, sprite nesting, menu and tutorial modes
  • Box2D physics worlds, bodies, controls, and collisions
  • scenes, transitions, data loading and saving, notifications, accelerometer

That’s one solid amount of stuff to cover in a beginner’s guide! Plus there’s a very nice appendix on introductory vector math applications, nice touch there. And these games are rather polished for tutorial examples. Indeed, our first criticism of the book is that they’re not up on the App Store for you to check out yourself what you’d be learning, which you may recall we thought was a pretty compelling feature of the Creating Games with cocos2d book. But hey, you can see screenshots on the author’s blog here.

Chapter 10 — “Code Once. Retire.” — yep, that’s what we’re probably here for … and it’s a bit of a disappointment. It covers how to set up an Android “Hello World” project skeleton with Eclipse, and some arrangements for hybrid Android/Mac compilation … and that’s pretty much it. For the intended audience, that strikes us as rather a flaw. What would make this a five-star book is if all the samples were available on the iOS App Store, as grumbled about last paragraph, but also on the stores for at least three or four of the platforms cocos2d-x targets, and discussion in the book of just what was involved in customizing the code, assets, and deployment tactics for each.

So, depends what kind of “beginner” you are how valuable you’ll find this.

“Beginner” to cocos2d from scratch? Easy five stars, buy it now.

“Beginner” to cocos2d-x with an oeuvre of cocos2d-iphone code you want to get shipped on other platforms? Useful, but just barely gets you started on anything but porting your Objective-C to C++ code, which chances are you could do on your own if you’ve ever programmed anywhere but the iPhone. If you do have a solid C++ history and at least nodding familiarity with Android project setup, three stars; if not, four stars.

So overall we’ll give it a solid four stars; some more followthrough on deploying the examples onto non-iOS platforms, and we’d give it an unreserved five stars.

Postscript — Other cocos2d-x Resources:

Those awesome iPhone Game Kit dudes have a game called Paralaxer deployed to all the popular stores that you can buy the source of, to go along with a free book in progress.

The Wenderlich archives have a recently updated Cocos2D-X Tutorial for iOS and Android: Getting Started and Space Game.

And digging around the project’s wiki and hub pages always might turn up something interesting too.

Continue Reading →
1

Tutorial: State Preservation and Restoration

If you’re like us and have been putting off puzzling out the State Preservation and Restoration stuff more or less indefinitely, here’s a great introduction to get you started on that:

State Preservation and Restoration

From the very first releases of the iPhone SDK Apple has encouraged developers to think about app startup and switching to make the experience as quick and transparent as possible for the user. The limited resources of mobile devices mean that App termination is a common occurrence. Returning to a previously running App that has been terminated by the system and finding it back at a startup screen is not a great user experience. The ability for an App to be suspended and resumed was introduced with iOS 4 and helps to reduce the problem but to make App termination transparent to the end user still takes developer effort.

There is a non-trivial amount of work required to save and then restore a deeply nested hierarchy of views and view controllers. Luckily with iOS 6 direct UIKit support for state preservation and restoration was introduced. This post is a collection of my notes on the basic steps to implement state preservation and restoration…

Supporting project at CodeExamples / Restorer for that and the followup

Restoration Classes and UIWebViews

I previously covered the basics of using state preservation and restoration but for the sake of brevity I did not provide an example of how to use a Restoration Class. This post will fix that omission and also take a look at how you can implement state restoration for a UIWebView…

Also note the current need to force reload tables, discussed here:

Bug Table View State Not Restored When Embedded in Navigation Controller

And there’s some extra nuggets to be gleaned here:

iOS State Preservation and Restoration

There, that should help you catch up with that new iOS 6 stuff just in time for iOS 7 to snow us completely under again!

h/t: iOS Dev Weekly!

UPDATES:

Checking Version and Device When Restoring State

Continue Reading →
0

UI Design and Asset Creation

So it’s been quite a while since we last mentioned anything to do with the design process, but we’ve noted a couple good posts recently:

Starters Guide to iOS Design

As someone who does work on both the development and design side of iOS apps I find that many designers struggle with the transition to UI work, or with the different processes involved in iPhone and iPad app design. In this guide I’ll describe the deliverables you’ll be expected to produce, outline the constraints of the medium and introduce fundamental iOS and UI design concepts…

Even if you’re not a starter, read it through anyway; it’s packed with all sorts of resource links and further references worth checking out.

My app design workflow

Here it is — my complete iOS, Android and Mac app design workflow, starting from the first time you open Photoshop, to the app release and beyond. Now seemed like a good time to document how I’ve been working, because my workflow is about to drastically change again, with the release of Skala.

There’s a Skala Preview out now that is well regarded, too.

Moving on to the asset creation side, big recent news is that TexturePacker thing which you’ve probably heard of is up to 3.0.11 these days which just added massively convenient integration with UIKit:

UIKit Animations with TexturePacker

UIKit applications often contain animations and lots of graphics. Adding the graphics as single images might consume a lot of memory and impede performance.

Using TexturePacker to create sprite sheets instead:

  • Reduces memory usage
  • Speeds up loading of your application

I’ve created some powerful classes which allow you to simply load the sprite sheets created with TexturePacker into your application – including code to play animations.

If you use animations that are pre-aligned, you might also have a lot of transparent pixels in your images. While the individual files might not use much memory – due to compression – the RAM usage might be quite big.

If you pack your sprite with TexturePacker this transparency can be removed. The provided CAWSpriteLayer class compensates the missing transparency by moving the sprite into the same spot as if it had its original size…

So yeah, now TexturePacker is good mojo for not just game makers but everybody working with lots of bitmap images. Oh, that would be … everybody, pretty much. So download it now!

… unless, of course, you want to skip the whole bitmap thing and go straight from vectors to code. We’ve kept a list of SVG options appended to this SVGKit mention a while back, but there’s one in particular worth pulling out for a more in-depth link collection, and that would be PaintCode:

PaintCode 1.3 is here!

For example, you may want to include real-life photos in your designs. We’ve added support for images to PaintCode to let you do just that…

PaintCode can now import layer graphics, paths, texts, groups and effects from Adobe Photoshop (PSD) documents…

And it’s file compatible with their new WebCode Canvas/CSS+HTML/SVG editor.

fabiankr / FKRBlockDrawing “is a collection of two classes and one category to make creating artwork in code a lot easier. It’s great in conjunction with PaintCode, where the graphics in the examples project are from.”

Recreating MKUserLocationView is a great walkthrough of how to do a tricky control that highlights the benefits of PaintCode nicely.

And of course make sure you check out their tutorials and examples.

Looks pretty darn useful, huh? Yep, we’re free with your money today; download it NOW!

UPDATES:

misterwell / MMScalableVectorView: “Turns static PaintCode or Qwarkee code into a UIView that honors the contentMode property.”

Generating all the icons you need quickly from SVG files – SVGtoIcons

How To Set Up Photoshop For UI Design

Continue Reading →
1

OmniPresence Open Syncing

So no doubt you read our post noting the fusterclucked state of iCloud syncing, and probably came away with a somewhat dispirited view of the document sync options for the small developer, yes?

Well, here’s something that you should be aware of if sync issues are even remotely on your radar — and they should be if you create any data! — looks like there’s a sweet spot for pretty much everybody on offer here:

Screen Shot 2013-05-22 at 8.42.14 PM.png

What does that mean exactly?

  • OmniPresence is a way to sync folders between your devices using a web server.
  • On Mac, a separate OmniPresence app churns away silently in the background, syncing any documents placed in its folders—without requiring any special support from other apps. On iOS, the sandboxing environment requires that each app add its own support for OmniPresence—so we’ll be providing free updates for all our apps (and publishing code so other developers can add support if they wish).
  • OmniPresence separates document syncing from any particular back end service provider. You can use it with your own compatible web server, or with the Omni Sync Server for documents created with your Omni apps.

Want someone else to host? Sign up here for the Omni Sync Server, or here’s a thread on suitable paid and free hosts.

What about self-hosting? Why, yes, downright trivial.

Where’s the client code? Right here, that would be.

Why should you trust this to work with your iOS apps? Because OmniOutliner and OmniGraffle and OmniGraphSketcher apps are using it, that’s why.

More architecture details to be found here:

OmniPresence, the Omni Group’s new cloud sync service, hits all the right buttons

… OmniPresence’s relevance in a sea of alternatives remains to be seen, but Omni seems to have hit on all the right features: privacy, simplicity, support for teams, and openness. This combination of factors could well conspire to make the company’s sync solution very successful, indeed…

And here’s a discussion from the user point of view:

The Omni Group Launches OmniPresence For Automatic Document Syncing

… More impressively, The Omni Group built OmniPresence in a way that documents are updated in real-time when an app is already running: in testing OmniOutliner for iPad alongside the Mac app, changes I made to a document were synced after seconds to the other app with the open document simply refreshing itself…

Pretty much upside all around, isn’t it? Looks like this should immediately go straight to the head of the list of alternatives to consider for pretty much all sync use cases you’re likely to be faced with!

Continue Reading →
1

Review: Developing Mobile Games with Moai SDK

So we’ve been vaguely aware of the Moai cross-platform SDK for a good while now, and been somewhat interested in learning more as its Direct Services and Custom Cloud Logic make it stand out a bit from the plethora of engine options available; so when the nice people over at Packt asked if we’d like to take a look at the first Moai book published, we were why yes this a good opportunity to polish up our knowledge of cross-platform options, no doubt our Dear Readers would be ever so interested in our thoughts!

5064OS_mockupcover_normal_1.jpg

Unfortunately, we were kinda underwhelmed. Not that it’s a bad book mind you — just of rather less scope than we were hoping for. Let us take the introductory section “Why Moai?” from the second page of the book, for those of you who didn’t click the links above to check out the Moai basics:

Moai SDK is a multi-platform game development framework. It’s been developed in C++ and all of its features are accessible through Lua. What does this mean? That you can build your game completely in Lua (taking advantage of the flexibility of this amazing language) and, in case you need low-level access, you can always switch to C++ and do whatever you want. You can even bind your C++ libraries to use them in your game, in Lua. It has built-in access to Moai Cloud as well, which is a cloud service that allows you to deploy server-side code written in Lua, with databases, support for push notifications, leaderboards, and other fancy stuff…

… and that’s the LAST mention in the book of Moai Cloud!! Très déçu. Since we see that as being the compelling reason one would likely pick Moai in the first place, we were rather hoping that would be covered in some detail. More detail than that single sentence, anyways. Well, on to what it does cover.

They have you install the SDK and install Zerobrane Studio and run the first project in the SDK /samples folder, and that all goes perfectly smoothly; then we have a chapter on the high level design philosophy, and on to walking through a Concentration-style game, which takes 4 chapters:

  • Chapter 4: Our First Game with Moai
  • Chapter 5: Showing Images on the Screen
  • Chapter 6: Resource Manager
  • Chapter 7: Concentration Gameplay

All pretty straightforward, especially if you already know Lua. And if you don’t, it doesn’t take much to figure out, which is kinda its point.

Chapter 8 “Let’s Build a Platformer!” introduces camera, parallax and sprite sheet animation. The next chapters straightforwardly introduce more functionality essentials:

  • Chapter 9: Real-world Physics with Box2D
  • Chapter 10: Creating a HUD
  • Chapter 11: Let the Right Music In!

And that’s it for your tutorials. Somewhat spartan, but the essentials of a single-player game are covered decently yes.

Chapter 12 is a fairly good chapter on how to get your Moai project compilable in Xcode for submission to the App Store; and Chapter 13 “Deployment to Other Platforms” … well, it’s not much more than a collection of weblinks. We really would have hoped that Windows, OS X and Android would have got the same deployment detail as iOS did.

So, yeah. On the one hand, if you have decided already to go with Moai, this will certainly help you through the learning curve associated with the free documentation — generally agreed as being somewhat lacking — quite a bit.

On the other hand, if you’re approaching it from the perspective we are, which isn’t “I’ve already decided, teach me how to use this” but “convince me why I should pick Moai over any of the other cross-platform kits available, particularly since I have several tens of thousands of lines of Objective-C cocos2d-iphone invested into already”, we would have needed

  • Walkthroughs of using Moai as a PaaS to provide social web services and cloud back end logic
  • Detail on how to integrate advertising, analytics, and other native SDKs
  • Much more detail on cross-platform deployment workflows

which you won’t find here. So that was rather a disappointment. Hard to qualify this book as “essential” without covering those points to the curious reader’s satisfaction, we think. But it is nicely written within the scope it does cover, so we’ll give it three stars, with the caveat that the cover says “the basics” and don’t expect any more than the basics. Then you should be satisfied with it nicely.

Continue Reading →
0

Tip: doesNotRecognizeSelector

Here’s a handy piece of the Cocoa runtime you might have overlooked the usefulness to your own code of:

doesNotRecognizeSelector:

Handles messages the receiver doesn’t recognize.

- (void)doesNotRecognizeSelector:(SEL)aSelector

The runtime system invokes this method whenever an object receives an aSelector message it can’t respond to or forward. This method, in turn, raises an NSInvalidArgumentException, and generates an error message.

Any doesNotRecognizeSelector: messages are generally sent only by the runtime system. However, they can be used in program code to prevent a method from being inherited. For example, an NSObject subclass might renounce the copy or init method by re-implementing it to include a doesNotRecognizeSelector: message as follows:

- (id)copy { [self doesNotRecognizeSelector:_cmd]; }

Came to our attention via this tweet suggesting that the exception-throwiing pattern there was a good one to adopt in your base classes for methods intended to be overridden. Well, true enough, although we generally tend to design our base classes so that there is sensible … or at least non-fatal … default behaviour; however, it struck us that one particularly hard to debug problem this pattern would save us from is people who create an object without using the designated initializer. Yeah, all those of you out there who work in teams larger than one are nodding in agreement there, aren’t you? Indeed, you can see from the “or init” mention in the discussion there Apple positively endorses that approach. We believe we’ll make an immediate resolution to adopt that practice from now on; if there’s a designated initializer, make it actually IMPOSSIBLE not to use it!

UPDATE:

If you ended up here looking for advice on the requiring calls to super problem … now the compiler deals with it for you!

Continue Reading →
0

iCloud Cuckoo Land

Sometimes idioms are just too apropos:

live in cloud-cuckoo land

to believe that things you want will happen, when really they are impossible

A common sentiment lately is to find iCloud CoreData syncing a particularly cuckoo land, as you may have heard:

Tom Harrington: iCloud: State of the Union

As some of you know, I’ve spent a lot of time over the past year working with iCloud in Mac and iOS apps. Specifically, working with Core Data’s built-in support for iCloud. I’m going to be doing a series of blog posts covering iCloud in various ways. Today I’m going to start off with an overview covering how iCloud is supposed to work with Core Data and a little about how it actually works in practice…

Daniel Pasco: The Return of NetNewsWire

As far as sync is concerned, we knew we would likely need an alternative to Google Reader as early as last year. At the time, the option that seemed to make the most sense was to embrace iCloud and Core Data as the new sync solution of choice. We spent a considerable amount of time on this effort, but iCloud and Core Data syncing had issues that we simply could not resolve…

Rich Siegel: The Gathering Storm: Our Travails with iCloud Sync

In general, when iCloud data doesn’t synchronize correctly (and this happens, in practice, often), neither the developer nor the user has any idea why.

Sometimes, iCloud simply fails to move data from one computer to another…

… While attempting to deploy iCloud sync on Mac OS X 10.7, we ran into a situation in which the baseline (a reference copy of the synchronization data) would become corrupted in various easily encountered situations…

…There’s no discernable consistency or rationale for when it says no and when it finally says yes … you can just keep trying, and eventually it might just work, or not.

Yikes! More discussion can be found at The Verge, and at Ars Technica, and here and there and everywhere, most wittily over at NSHipster; but let’s just settle for declaring it a given that people much better at this programming stuff than you are can’t make iCloud CoreData sync work, so neither will you.

However, it’s also getting close to a given these days that Your App Needs to Sync:

If your app deals with users’ data, building cloud sync into your app should not be a feature you bolt on to an app – it is the feature. It’s why you will beat competitors or lose hard to them. It’s what will make your app feel effortless, thoughtless, and magical. It’s what will gain a user’s trust, and once you have that, they will sing your app’s praises and never give it up. But to earn that trust, you have to account for sync at every step of the design and engineering of your app.

Developers have a number of choices as to how to build an app around sync. You can use iCloud, you can use a hosted service like Parse, or you can build a custom sync service for your app. Each solution has trade offs. So what should you optimize for?

The reality is that every app is different, and each sync system must cater to the data that is syncing. While it is certainly the most work, it’s my belief that you should optimize for control. You should have total and complete control over when and how your app syncs its data. You should be handling errors and conflicts, not abstracting them behind black-box middleware. Without this level of integration, you’re bound to a system that can fail unreliably, leaving users to figure out what went wrong. And when they try, it’ll be your app that feels broken.

Indeed. Read that whole article, it’s got the choices and tradeoffs discussed quite nicely.

For an enthusiastic exposition of the DIY extreme, check out Why Developers Shouldn’t Use iCloud Syncing, Even If It Worked:

You may think you’ll never want an Android or browser-based version of your app. But are you sure? Really, really sure?

You hope your app will be a hit. (If not, then quit writing it and choose something else.) If it’s a hit on iOS, it could be a hit on Android too — and you can bet that customers will ask for a web app version.

You don’t want to limit the success of your app just because you didn’t want to write your own server…

Well, there’s that. On the other hand, those of us who are not superhuman are challenged enough to write an app that works, never mind a server to go with it, and it limits the success of your app a good deal more to have it not released in a timely fashion, yes?

Splitting the difference, there’s the various backend as a service stuffies one could use; but just for the purposes of finishing off this post in a timely manner, let’s take it as given that your initial release is built around CoreData in the app, and you just want get sync working with that as quickly as you can with acceptable reliability. We’ve pretty much established here that iCloud’s out. What to do? What to do?

Well, here’s a few options that look worth a gander for that:

nothirst / TICoreDataSync is what Moneywell uses for Dropbox-based syncing:

TICoreDataSync is a collection of classes to enable synchronization via the Cloud (including Dropbox), or local wifi (coming soon), of Core Data-based applications (including document-based apps) between any number of clients running under Mac OS X or iOS. It’s designed to be easy to extend if you need to synchronize via an option that isn’t already supported…

AFNetworking / AFIncrementalStore eliminates sync problems by storing only in the cloud, which does make things simple if you can declare network access a requirement:

AFIncrementalStore is an NSIncrementalStore subclass that uses AFNetworking to automatically request resources as properties and relationships are needed.

Weighing in at just a few hundred LOC, in a single {.h,.m} file pair, AFIncrementalStore is something you can get your head around. Integrating it into your project couldn’t be easier–just swap out your NSPersistentStore for it. No monkey-patching, no extra properties on your models…

WasabiSync is a paid service that claims “Add seamless cloud synchronization to your Core Data based iOS app in less than an hour…”

Wasabi Sync monitors your existing Core Data persistent store and watches for when your application makes changes to it. When changes occur, Wasabi Sync serializes the changes and sends them securely over the cloud to the Wasabi Sync servers. Those changes are then propagated to the user’s other devices and written to their respective persistent stores.

Wasabi Sync requires almost no code changes to integrate with your app. The only things you have to do to start syncing are:

Add the Wasabi Sync SDK to your existing Core Data based project.

For any Core Data entities you want to sync, add a globally unique identifier to your models.

Specify that your syncable core data entities implement the WHISyncableObject protocol.

That’s pretty much it!

Simperium is another paid service whose flagship demo is Simplenote. Documented here:

Simperium iOS / OSX is a bit like iCloud: you can use it to easily move data among iPhone, iPad, and Mac versions of your app. But you can also:

  • Move data to non-Apple versions of your app
  • Retain control of your users and data
  • Build backend services
  • Earn money by selling more storage to your users
  • Brand these capabilities as your own

How it Works

Simperium can work with Core Data or JSON data stored in NSDictionary objects. As your users interact with your app, Simperium efficiently aggregates changes and moves them through our hosted, scalable service.

Changes are moved to and from Simperium as soon as possible. In the case where all devices are online, changes are moved in realtime. In the case where one or more devices are offline, data moves as soon as those devices come online. Conflicts can be resolved automatically.

Although the Simperium service hosts your app’s data, you retain control. You can host your own services that can see and store all data that moves through the system…

Interestingly, Simperium was recently acquired by Automattic:

As mentioned in our post on the Simplenote blog, Simperium has been acquired by Automattic! We’re really excited about this and what it will mean for the platform.

Automattic and WordPress are huge proponents of open source software so we’re happy to be able to go forward with our plans to open up the code, starting with the iOS and JavaScript client libraries. In the short term we’ll also be moving to faster hardware, so overall performance and stability of the hosted service should improve.

We’re going to keep expanding Simperium as a tool for building apps. Adding Simperium to apps that can work from a local datastore lets you automatically synchronize data across different instances and platforms. This way of building apps feels natural, a model where the developer can focus purely on the data itself, not networking or APIs. Synchronizing data is just part of the problem though. We’ll be adding better support for things like binary syncing and collaboration, along with a wider variety of client libraries…

One could be justifiably skeptical that interoperation with Core Data is likely to remain a priority at Simperium going forward. But maybe it will. And in any case, hey it’s open sourced so help out or fork it if you like.

Any experience with any of these solutions, Dear Readers? Or know of any CoreData-focused cloud syncing approaches we’ve missed here?

UPDATES:

iCloud Complications, Part 1 and Part 2 and Part 3 and as She is Spoke

Does Core Data Sync Quack?

UbiquityStoreManager: Solving the iCloud for Core Data problem

Clear in the iCloud

Core data peer-to-peer synchronization

Use a Google Spreadsheet as your JSON backend if, you know, you don’t really need serious data at all…

objc.io #10: Syncing Data

(TL;DR: iCloud Core Data for 7.0+ only is usable!)

Continue Reading →
4

UDID Replacement

So as you all are panicking to get your UDID-replacing code submitted before May 1st Doomsday, might want to check out

The Developer’s Guide to Unique Identifiers

We had been warned that uniqueIdentifier was going away, and now Apple is giving us not just one but two alternatives to use. But which one should you use and when is it appropriate to choose one over the other? The documentation doesn’t answer these questions and it is left up to you to decide what is best for your applications’ purposes.

I am going to outline each of the iOS supported and deprecated unique identifier methods to explain what they do in hopes of arming you with the knowledge you need to make the right decisions…

Just in case there’s anything there that you might have overlooked so far.

Now, that article does omit the SecureUDID solution that we thought looked pretty nifty last April, so if you’re not going forward with IDFA/IDFV only, might want to give that one a look over as well.

Continue Reading →
0

ReactiveCocoa

Noticed mentions of this “ReactiveCocoa” thing popping up all around lately? Yeah, us too. Let’s take a bit of a look at what that is exactly, shall we?

ReactiveCocoa / ReactiveCocoa: “is an Objective-C framework for Functional Reactive Programming. It provides APIs for composing and transforming streams of values.”

Not feeling the excitement yet? Understandable. So what is this FRP thing exactly?

Functional Reactive Programming (FRP) is a programming paradigm for writing software that reacts to change.

FRP is built on the abstraction of values over time. Rather than capturing a value at a particular time, FRP provides signals that capture the past, present, and future value. These signals can be reasoned about, chained, composed, and reacted to.

By combining signals, software can be written declaratively, without the need for code that continually observes and updates values. A text field can be directly set to always show the current timestamp, for example, instead of using additional code that watches the clock and updates the text field every second.

Signals can also represent asynchronous operations, much like futures and promises. This greatly simplifies asynchronous software, including networking code…

If that’s a bit too abstract to get a handle on easily, NSHipster has a nice layman’s intro:

ReactiveCocoa is comprised of two major components: signals (RACSignal) and sequences (RACSequence).

Both signals and sequences are kinds of streams, sharing many of the same operators. ReactiveCocoa has done well to abstract a wide scope of functionality into a semantically dense, consistent design: signals are a push-driven stream, and sequences are a pull-driven stream…

So, it’s basically fancy-pants KVO, then? No, that’s underestimating it, check out this ReactiveCocoa: First Impressions post:

‘So what?’, I hear you say, ‘It’s a nice wrapper for KVO, big whoop’. Well, it gets better: in addition to a simply KVO API, ReactiveCocoa lets you express complex conditional behaviours.

GitHub’s example is as follows:

[[[[RACAbleSelf(self.username) distinctUntilChanged] take:3] where:^(NSString *newUsername) { return [newUsername isEqualToString:@"joshaber"]; }] subscribeNext:^(id _) { NSLog(@"Hi me!"); }];

Here’s their explanation of what’s going on:

We watch username for changes, filter out non-distinct changes, take only the first three non-distinct values, and then if the new value is “joshaber”, we print out a nice welcome.

Using KVO alone this simple isn’t possible: we would need to track and retain the value of username to compare it with the new value and keep a counter around to increment every time we receive a non-distinct value. This would certainly be more than six lines of code…

OK, so it’s like KVO, plus Cocoa Bindings, except not sucking. Well, that is pretty nifty. Definitely something to try out next time we have a complex pattern to implement!

Here’s some more discussion posts worth reading:

Input and Output

Better Code for a Better World : “… an introduction to using ReactiveCocoa to solve all of the problems currently facing mankind—a phrase I only use somewhat facetiously…”

Basic MVVM with ReactiveCocoa

And some coding samples:

ReactiveCocoa / ReactiveCocoaIO: “a framework for accessing and manipulating a file system through signals…”

ReactiveCocoa / ReactiveCocoaLayout: “a framework for describing Cocoa and Cocoa Touch layouts in a reactive way…”

uasi / AFNetworking-ReactiveCocoa “makes AFNetworking reactive.”

UIButton Edge Insets has both RAC and non-RAC implementations of button editing code.

Machx / Reactive-Cocoa-Playground: “a collection of useful and sometimes experimental ReactiveCocoa code.”

UPDATES:

Functional Reactive Programming on iOS with ReactiveCocoa and Getting Started with ReactiveCocoa

ReactiveCocoa UIKonf 2013 presentation slides

ReactiveCocoa Essentials: Understanding and Using RACCommand

Tutorial: Building A Weather App With Functional Objective-C Programming Using ReactiveCocoa

Replacing the Objective-C “Delegate Pattern” with ReactiveCocoa

Video Introduction To ReactiveCocoa And Tutorial On Reactive Cocoa In A Data-Driven Application

ReactiveCocoa Tutorial – The Definitive Introduction: Part 1/2 and Part 2/2

If KVO is right, why does it feel so wrong?

Continue Reading →
3

Tip: Computing Tilt

Here’s an excellent tutorial on how to compute device tilt using Core Motion and quaternions:

Computing the iOS device tilt

“Quatta-whatons”, you ask? Why:

The beauty of Quaternions

If you don’t know what a quaternion is yet, please don’t be afraid by this strange word that seems right out of Star Trek.

Quaternions were first described by Hamilton in 1843 and applied to mechanics in three-dimensional space.

It eases the way we deal with the orientation of a body in a 3D space, and is better suited than the Euler angles that Apple is computing for us because of three reasons :

  • it’s easier to compose rotations or to extract values from it.
  • it avoids the gimbal lock problem.
  • and Apple provides a quaternion in the CMAttitude class instance.

And because we only want to compute the yaw we do not have to worry about the gimbal lock problem, since our goal is not to described the complete iPhone orientation in the 3D space but only the tilt…

Eyes glazing over yet? For a practical example of how to add some niftiness to your app with all this, check out

dulaccc / DPMeterView: “Gravity-aware gauge-style meter view with delightful animations.”

iphone-with-gravity.png

h/t: @romainbriche!

Continue Reading →
0
Page 7 of 96 «...56789...»