You are browsing the archive for Xcode.

Profile photo of marc

by marc

Data Abstract and RemObjects SDK for Cocoa on iOS 7 and the 64-bit A7

September 30, 2013 in Data Abstract, iOS, Xcode

Hi. I wanted to give you a quick update on the status of Data Abstract and RemObjects SDK with regards to both the new iOS 7.0 and – more interestingly – the new 64-bit iOS on the iPhone 5S.

Over the past couple of weeks, we have been debating whether we should make a small interim update to RO/DA for Cocoa available to “officially” support the two new platforms/technologies, and we have decided against such an update, for the following reasons:

We’ve (of course) been testing the RemObjects SDK and Data Abstract code base with iOS 7.0 since the first beta, and with 64-bit since the iOS 7 GM and the iPhone 5S is out. The current code base as shipped in the Fall release about a month ago is working perfectly with iOS 7, and no changes are needed.

It is also working fine on 64-bit (ignoring some minor warnings), as expected – after all, the same code base has been running on 64-bit Mac OS X since forever. Still, it would be nice to ship an update release that contains a universal binary pre-compiled for arm64 out of the box, but there’s one downside to that:

Right now, if we switched RO/DA to build for arm64 by default, that would mean we’d also need to set the minimum deployment target to iOS 7 – which in turn means the binary we’d ship would not allow you to build applications that still target iOS 6 (or lower), something we know many of you still do.

On the flip side, for those of you who would like to build your RO/DA based apps for 64-bit, it is a simple job to rebuild RO/DA yourself: Simply open the project in Xcode, change the architecture to ARCHS_STANDARD_INCLUDING_64_BIT (and clear the deployment target, of course), and hit rebuild. (We’re also making a pre-release build available today that does have 64-bit enabled (at the cost of losing deployment target options, as indicated.)

Apple is promising to sort out the deployment target situation “next month” to allow arm64 to co-exist with older deployment targets, and we figured it would be best to hold out for that — especially given how easy it is for you to manually rebuild for 64-bit now, if you need it.

I will keep you posted as this develops – and once again, us holding back on shipping the update does not mean that the current code base you have now is not perfectly fine for arm64 use already.

Let us know what you think.

Profile photo of marc

by marc

iOS 7 and OS X Mavericks

June 17, 2013 in Cocoa, Data Abstract, Elements, iOS, Mac, WWDC, Xcode

As you have probably heard by now, last week Apple announced iOS 7 and OS X Mavericks, new major versions of both its flag-ship operating systems. I had the privilege of being on site in San Francisco and attending WWDC in person, but the keynote with the core announcements is available for public viewing by anyone, and the remaining ~100 sessions of the conference are also available for free to all registered developers (major kudos to Apple for that, and more importantly, for making these videos available so fast, in most cases on the same day as the actual presentations!).

iOS 7 is a major new release and – most observers agree – a game changer. It’s a whole new UI paradigm for the OS, and will be a very exciting release for both users and developers; there are a whole bunch of new technologies that will let you create even better iOS apps, and will make the whole iOS experience even better for the user — in the core OS or with your apps.

Due to the massive UI overhaul, most iOS apps will need a serious rethinking for iOS 7 to stay relevant – which means extra work for developers, but also extra opportunities. From what i can tell (and am allowed to tell), switching an application over to the core iOS 7 “look” will be simple, but really making an app feel at home on iOS7 will require a lot of thought — no way around it.

I have already started moving two of our (internal) apps to iOS 7 while on site in San Francisco, simply because after (foolhardily) upgrading my main phone to the new OS, i could no longer stand looking at the old UI ;). One app is “done” and was relatively straight-forward – mainly a matter of rebuilding with the iOS 7 SDK, and making a few adjustments here and there to better embrace the new style; the other will be more work.

OS X Mavericks (if you don’t like the name, you are not alone. Virtually everybody i talked to or heard talk about it found it “weird”) is a smaller upgrade, by comparison, but also a significant release with a ton of exciting technologies for developers – two that were highlighted in the keynote include the new Maps API and cool new energy-saving APIs and technologies. (And if you’re not excited by being able to make your apps more power-efficient, then you have no business developing Mac apps! ;).)

Of course the big question you’re all asking is how Oxygene for Cocoa is working with the new iOS 7 and OS X Mavericks. The good (and slightly unexciting, because expected) news is: it works just fine. We’ve long had an article on the Wiki that discusses the (simple) steps for hooking up Oxygene with new beta SDKs, and Oxygene is working fine with iOS 7 and with Mavericks (although i do recommend grabbing the latest beta drop of Oxygene, as we already made some tweaks and improvements there).

All the new APIs (IIRC Apple mentioned a number of 1500 new APIs being available) will work with Oxygene out of the box – no need to wait for anyone to create any wrappers or headers for you, and re-building your Oxygene apps with the iOS 7 SDK will give you the new iOS 7 look right away (but not save you from re-examining how to really embrace iOS 7 best with your app, of course).

There are also a few new non-API features that we’ll be embracing with Oxygene as well, but unfortunately those are (afaict) all under NDA, so i cannot talk about them yet. But suffice to say over the next few months we will of course be doing a lot of testing with Oxygene and the new APIs and SDKs to keep Oxygene up to date with the SDKs and the Xcode 5 tool chain.

Of course we’ll also be testing Data Abstract and RemObjects SDK for Cocoa with the new SDKs, and (where applicable) expanding them with support for new APIs. In my testing so far, they work great (both the apps i mentioned above are DA-based, and run fine on iOS 7, for example).

Support

Talking about new iOS and OS X SDKs is always a tightrope walk, as there’s a lot of information that’s under NDA (but available to all registered Apple developers – so do make sure you check out the beta builds and all the videos from WWDC). But Oxygene, as well as RO/DA for Cocoa, are already working great with the new operating systems, and we’ll be working hard to expand those parts that do need explicit support and work to fully embrace the new OSs.

If you have any specific questions regarding support for or issues with the new SDKs, there’s two places to get help: for one, we’ll be monitoring and participating in Apple’s beta forums, so you can post questions about Oxygene there (maybe add “(Oxygene)” to the subject so we can find them easier). And you can also always directly email support.

We cannot discuss the iOS 7 or OS X Mavericks Beta SDKs on Connect; you could be violating your NDA by posting details there, and we’d be doing the same by answering. So be careful.

Summary

I’m very excited about both iOS 7 and Mavericks (and i assume i’ll eventually get over the name, too), and so should you. I’m looking forward to seeing what you’ll build on the new OSs with Oxygene and Data Abstract.

Profile photo of marc

by marc

Cocoa/CoreFoundation Bridging Explained

April 2, 2013 in Cocoa, Elements, iOS, Nougat, Xcode

“Bridging” is a new language feature introduced to Objective-C alongside ARC, that i believe is not very widely understood, at least not fully.

Cocoa always had the ability to “toll-free bridge” between Cocoa objects, such as NSString and their underlying non-object-oriented CoreFoundation equivalents, like CFStringRef. Before ARC, you could just cast back and forth between them as you pleased, but ARC made the rules a bit stricter, and Objective-C introduced new “bridge casts” to formally express these toll-free bridge casts in an ARC-safe manner. Oxygene also supports these casts, with the bridge<T>() compiler magic function.

Questions?

So how do bridge casts work, when do you need them, and what is the difference between the three distinct types? That are questions that i think a lot of people are confused about. I’ll admit i myself wasn’t quite sure what the differences and implications of “bridge” vs. “transfer” vs. “retain” were, until Carlo and i sat down the other day to really formalize how we would properly expose them in Oxygene (and thus had to understand them really well ;)).

As most Objective-C developers who use ARC will know, the answer to the middle question is the easiest. When do you need a bridge cast? Simple: every time you want to go from a Cocoa object to a CoreFoundation entity or back. You know this, because the compiler will tell you by refusing to compile code that was perfectly fine in pre-ARC, such as:

NSString *s = (NSString *)myCFString;

Instead, you now need to write:

NSString *s = (__bridge NSString *)myCFString;

Or do you? The answer is, it depends. As i mentioned before, there are three different types of bridge casts, and it is important to pick the right one (lest you will end up in the land of chasing down memory leaks and weird crashes, once again).

I say there are three types, but you can really think of them as two groups of casts.

“Regular” Bridge Cast

First, there’s what i like to think of as the “regular” bridge cast. In Objective-C that’s expressed with the __bridge keyword; in Oxygene, it’s the default when calling bridge<T> without a BridgeMode enum value (or with BridgeMode.Bridge, the default):

Objective-C

UIColor *u = [UIColor redColor];
CGColorRef c = [u CGColor]
id o = (__bridge id)c;
[u set]; // or something else that keeps "u" around.

Oxygene

var u := UIColor.redColor;
var c := u.CGColor
var o := bridge<id>(c);

You can think of this as making the original item (a CGColor) available “on the other side” (as featureless “id”, in this case, as CGColorRef is not toll-free bridged to a Cocoa class), without affecting the original.

The original ownership of the CGColor remains with the UIColor object it was obtained from. The cast object is merely a second view onto the same item, in a different form.

The “regular” bridge cast works both ways — going from a Cocoa to a Core Foundation, or the other way around.

Transfer/Retain Bridge Casts

The second type of casts are the transfer/retain bridge casts casts. I lump them together because they form two sides of the same coin. Different than the regular bridge cast, they do not work in both directions; instead, the transfer bridge cast can be used when going from CoreFoundation to Cocoa, and the retain bridge cast when going the opposite way, from Cocoa to CoreFoundation.

In Objective-C that’s expressed with the __bridge__transfer and __bridge_retained keywords; in Oxygene by calling bridge<T> with a BridgeMode.Transfer or BridgeMode.Retained value.

Why this distinction is necessary will become clear soon, but first let’s look at an example:

Objective-C

CFStringRef c = CFStringCreateWithCString(nil, 'hello', CFStringGetSystemEncoding());
NSString *s = (__bridge_transfer NSString)c;
c = nil;

Oxygene

var c := CFStringCreateWithCString(nil, 'hello', CFStringGetSystemEncoding());
var s := bridge<NSString>(c, BridgeMode.Transfer);
c := nil;

As the name implies, the transfer cast transfers the item, and its ownership, to the other side. After the cast from the CFStringRef to an NSString, the NSString (stored in “s”) is the only true owner of the underlying string. The original CFStringRef is no longer relevant, and as you see, we do not (must no) free it.

Essentially, the transfer cast says, “give me a Cocoa object, and then let’s forget the CoreFoundation thing ever existed”.

This is highly useful when writing more concise code. In the example above, we could have used a regular bridge cast, and simply called CFRelease(c) afterwards and everything would have been fine. But imagine the same example written as a single line of code:

Objective-C

NSString *s = (__bridge_transfer NSString)CFStringCreateWithCString(nil, 'hello', CFStringGetSystemEncoding());

Oxygene

var s := bridge<SString>(CFStringCreateWithCString(nil, 'hello', CFStringGetSystemEncoding()), BridgeMode.Transfer);

Here we have no reference to the original CFStringRef object, so the transfer cast is essential.

Conversely, you can imagine that using the transfer cast on the CGColor example above would be disastrous. The Original CGColorRef is owned by the UIColor we received it from; we’d have no right to transfer it and invalidate it underneath the UIColor’s feet. Things will crash, eventually. (In fact, a bug report with just this problem that we received from a tester of Oxygene was what promoted me to write this post ;)).

At this point, you might already begin to understand why transfer bridge casts can only work one way in an ARC language and why on the flip side the retain bridge casts is needed:

Objective-C

NSString *s = [NSString stringWithFormat:"hello, %@", name];
CFStringRef c = (__bridge_retained CFStringRef)s;
...
CFRelease(c);

Oxygene

var s := NSString.stringWithFormat('hello, %@', name);
var c := bridge<CFStringRef>(s, BridgeMode.Retained);
...
CFRelease(c);

When we used transfer bridge casts above, a true transfer happened; the CoreFoundation reference was no longer valid, and we did release it. Going the other way, we do not have this luxury: The original Cocoa object (a string in this case) is managed by ARC, and there is no way to not release it. If a true transfer bridge cast were allowed, ARC would go ahead and over-release an “invalid” object. And that cannot happen.

Instead, the retained bridge cast does the next best thing. It gives us back a CoreFoundation entity we fully own (and have to release), and it leaves the Cocoa object untouched.

You can think of the retain bridge cast as “just like the transfer, but leaving the source object for ARC to deal with”.

When to Use What?

The answer to this question will not always be clear-cut, but a good rule of thumb is to use the regular bridge cast — i.e. __bridge or bridge<T>() w/o mode — when you do not own the original item and/or are merely “borrowing” it to be used on the other side. Use the transfer/retain bridge cast when you do own the original object and want to take ownership of it “on the other side”.

So How Does this Work Under the Hood?

To be honest, you probably don’t really want to know, or at least not think about it, because what the bridge casts do under the hood can be really confusing how you think of them on the higher level.

Let’s start with the transfer bridge cast. It essentially does “nothing”, just as the regular cast would have done before ARC; it converts the pointer type and that’s it, and it does not affect the retain count of the object at all.

Because of how ARC works under the hood, it assumes ownership (or a +1 retain count, if you will) of the Cocoa object pointer and this affectively acts as if the original CoreFoundation object had been released (i.e. gotten a -1 on its retain count). The actual retain count of the item has not changed, but ARC now has staked claim on it.

The regular bridge cast is essentially the same as the transfer, except it does an extra retain on the resulting object when going from Core Foundation to Cocoa. This way, ARC can deal with the object (and eventually release it again). But the underlying CoreFoundation reference is unaffected and keeps its own claim on the entity. When going from Cocoa to CoreFoundation, it does nothing — because ARC is not involved in handling the life cycle of CF objects, it can just pass the original object off as an unowned entity.

Finally, the retain cast works much like the regular bridge, but does an additional retain on the item, before the cast. This way, the original object reference remains retained, and the resulting CF entity is owned (i.e. needs to be freed) as well.

The thing to keep in mind is that there’s a single retain/reference count for each entity. It’s really just a sleight of hand on the compiler’s side how the bridge casts “move” the ownership around between the Cocoa and CoreFoundation references.

But as i said, you probably want to forget about these implementation details, and just think of these bridge casts in the logical terms described above ;).

Summary

I hope you found this article useful and that it helped to provide some insight into the different bridge cast types on the Cocoa platform. Let me know what you think!

Profile photo of marc

by marc

Creating a Turn-Based Game for iOS: Nougat Tic-Tac-Toe

March 11, 2013 in Elements, iOS, non-tech, Nougat, Oxygene, Visual Studio, WWDC, Xcode

Over the past couple of weeks, i have been working on a new sample project for Oxygene “Nougat” on the side. After having gotten Browse500 into the App Store in January and showing how to reimplement a simple native UIKit control from Objective-C in Nougat last month, i wanted to create another example that illustrates the benefits of how Nougat interacts directly with the native APIs, and i picked a technology i knew nothing about at all to do so: Game Center.

I’m not a big gamer; i don’t find myself playing games much, and i have certainly never written one before, so this was a great opportunity to explore something new.

For those of you not familiar with it, Game Center is a technology Apple ships in iOS (and now also Mac OS X) that allows for games to interact across the network to create multi-player games, and to keep track of achievements. Game Center is not about graphics, or game UI, or anything of the sort (there’s other frameworks for that), it’s only for bringing players together.

I decided to create a simple turn-by-turn game, that is, a game where multiple players (in this case two) can interact, but only one player is active at a given time. Once a player has made their move, it’s the next player’s turn. To keep things simple, i picked a game that everybody knows and that is dead simple to implement, game playing wise: Tic Tac Toe. This way, having to explain the game itself won’t get in the way of the sample code.

To start with, i had to dig myself into the Game Center documentation and i watched a couple of videos on Turn-by-Turn gaming from WWDC 2011 (sessions i didn’t attend at the time). As it turns out, the API for interacting with Game Center for such a game is surprisingly easy and straightforward, and i was up and coding in no time.

Before we get started looking at the code, let’s look at the prerequisites:

  • Here’s the amount of effort anyone from the Oxygene team had spent on thinking about or working on making GameKit (the framework for interacting with Game Center) available to Nougat, before i started this endeavor: 0. Nada. Nil.

  • Here’s the amount of legwork i had to do before i could work with the GameKit APIs, just like every other Cocoa developer would: i added a reference to GameKit to my project. Done.

That’s it. No begging someone to translate header files, or waiting for someone to create a crappy abstraction wrapper class. Add a reference, and use the APIs as Apple intended them — that’s the way development should be.

The Code

Let’s dive into the code.

First of all, the full code of Tic-Tac-Toe is included in the latest Nougat beta, and it’s also available in my Github account for anyone to explore.

There’s really three separate parts that are of interest as a sample project in this app:

  1. The GameKit integration
  2. The game board, implemented as a custom UIControl
  3. The computer player algorithm, generously provided by my good friend and long-time Oxygene user, Jeremy Knowles.

Let’s look at GameKit first.

Working with GameKit

There’s four main classes or concepts that you will work with for GameKit.

The first is the local player, a singleton object that can be obtained via a call to GKLocalPlayer.localPlayer. This objects provides the game with information about the local player — most importantly their ID, and whether the local player is in fact registered and authenticated with Game Center or not. If the player is not set up for Game Center, Tic Tac Toe will simply disable the appropriate UI and just allow local vs. computer game play (although it would be possibly for a game to provide a signup UI, if so desired).

Next is the GKTurnBasedMatchmakerViewController, which provides access to the standard GameCenter UI. It gives the user access to any and all games they might already have going on, as well as the chance to start a new game. In Tic-Tac-Toe, i make this UI available via a button in the navigation bar, and all that’s needed to show the view is code like the following:

var request := new GKMatchRequest;
request.minPlayers := 2;
request.maxPlayers := 2;
 
var mmvc := new GKTurnBasedMatchmakerViewController withMatchRequest(request);
mmvc.turnBasedMatchmakerDelegate := self;
mmvc.showExistingMatches := true;
presentViewController(mmvc) animated(true) completion(nil);

This code brings up the Game Center UI, with the list of games (if any) or straight with the “Start New Game” (if not). Via the GKMatchRequest, we force the number of players to exactly two. (Game Center itself allows games for up to 16 players):

Tic Tac Toe Game Center

The way Game Center works for starting new games is that it lets you either invite a known friend who also plays the game or — much more interestingly — auto-match you with another random player. One thing that’s cool is that after starting a game, it will always be your turn — you will either be thrown into another game that was started earlier by a different user, or you will get to start a fresh game, depending on what games are currently live and waiting for players. If you start a fresh game, you get to make your first move, and then and only then does Game Center go out and try to find someone for you to play with.

Going back to the code level, what we are looking out for is a callback on the turnBasedMatchmakerDelegate that we assigned above. Our root view controller class implements some 4 methods from the IGKTurnBasedMatchmakerViewControllerDelegate interface, and the match-maker view controller will call us back on these when interesting things happen. This is a very common pattern in Cocoa, and is how the platform handles “events”.

In particular, the callback we care about for starting a new game is:

method turnBasedMatchmakerViewController(aViewController: GKTurnBasedMatchmakerViewController) 
       didFindMatch(aMatch: GKTurnBasedMatch);

This method actually gets called any time the user picks a game in the Game Center UI — whether they are starting a new game, or selecting an existing game. This is neat, because it means we can leave all the game management to GameKit, and don’t need to keep track of ongoing games ourselves.

This callback receives the third important class, a GKTurnBasedMatch. “All” we need to do when this method is called is load the passed match as the active game. In the Tic-Tac-Toe app, we do this by calling our own loadCurrentMatch() method, which does all the heavy lifting.

Every match contains a binary blob in the matchData property that describes the current game state. The content of this binary blob is entirely up to our game, but we can use it to store up to 4KB of data, and this data will automatically be passed between all the participants as they take their turns. In turn, our Game will read the data, let the active player make their move, and then store the updated game state, as we will see in a few moments.

Loading a Game

Loading a game is done with two method calls, first, a a small helper function loads the binary data into an NSDictionary, and then we ask the board to load its game state from that dictionary (the idea being that in a future version, our game might store additional info in the dictionary that the board does not care about — that’s why i decoupled the data the Board class reads/writes from the actual binary format).

var lDictionary := dictionaryFromData(fCurrentMatch.matchData);
fBoard.loadFromNSDictionary(lDictionary,);

The same happens in reverse when we later save the updated game state. Of course, when a new game is first started, there will be no data present (GameKit doesn’t know anything about how our game data is structured, after all), so our code will need to be prepared to find an empty NSData object in matchData.

The second part, in addition to loading the board data, is determining the active player (if any) and enabling the game play. Each GKTurnBasedMatch has a currentParticipant property of type GKTurnBasedParticipant which links to the current player (it also has a participants array that contains all (two) players). We can compare this participant’s playerID to that of the local player.

If they match, it’s the local player’s turn, so we display “your turn”, and enable the board. If they don’t match, it’s either the remote players’ turn (if currentParticipant is assigned), or the game has finished. In either case, we show the proper status message, and leave the board disabled.

Playing a Turn

If it was the local player’s turn and we enabled the board, we’re done for now, and await the player to make a move. This all happens inside the Board class, which will call us back via the board() playerDidSelectGridIndex() method, once the player made their move.

What we need to do then is determine the game status (the player might have made a winning move, for example), re-encode the game status, and pass control back to game center.

There are three scenarios we need to cover:

  1. The player has won by managing to place 3 “X” markers in a row.
  2. The board has been filled (and the game just tied).
  3. Any other case — the game is still on.

In the two game-over scenarios, we set the appropriate status (Won/Lost/Tied) on each of the game participants, and then call endMatchInTurnWithMatchData() completionHandler() to tell Game Center that the match has ended as part of the player taking his turn.

In the other case, we call endTurnWithNextParticipant() matchData() completionHandler() to let Game Center know that the local player is done, and game play can move to the next player.

In either case, we will pass the updated information on what our game board looks like now, via the matchData parameter.

It is worth noting that it’s up to our game to tell Game Center “who’s next”. In our case, that decision is trivial (it’s the player that’s not the local player), but Game Center allows for turns to be passed in arbitrary ways, depending on your game’s needs — it doesn’t always have to go around the (virtual) table.

Once we called either of the above fund methods, it’s no longer our turn, and all we can do is wait for the remote player to make a move.

Handing Remote Turns

Of course, eventually the remote player will make their move, and GameKit provides a second delegate interface for this case, IGKTurnBasedEventHandlerDelegate, which we have hooked up to the GKTurnBasedEventHandler.sharedTurnBasedEventHandler singleton.

What will happen once the remote player moved is that Game Center will show a notification banner to the user, saying something along the lines of “It’s Your Turn”, and play that annoying fanfare sound. When and only when the user taps that notification, will we receive a call to the

method handleTurnEventForMatch(aMatch: GKTurnBasedMatch) 
       didBecomeActive(didBecomeActive: Boolean);

method to let our application know that something happened. This is nice, because it saves us from worrying about showing any UI to the user to ask if they, say, want to switch from the game they are currently looking at to the one that has received a response. When we get the callback, we already know that the user has decided to view the game in question.

So all we really need to do is the same as we did in … didFindMatch() above: load the passed match and enable the board, if appropriate.

House Keeping

This basically takes care of all the Game Center interaction needed for our simple game. There’s a few more minor items that i won’t go into detail for this post; for example, there’s a callback you will want to handle to quit games if the user selects to delete them in the Game Center UI. There also are APIs for providing a custom UI for the list of games, instead of relying on the standard UI provided by Game Center (all Tic-Tac-Toe does with this is adjust the Game Center button to either read “Games” or “Start”, depending on whether there are any games ongoing or not).

In Tic-Tac-Toe, all the GameKit interaction is located in RootViewController.pas, which is only ~500 lines of code total, so it should give you a good overview and starting point for your own game.

Caveats

There are a couple of caveats you might want to be aware of when working with Game Center games; these had me stumped for a short while, so hopefully pointing them out here will help save you frustration:

  • In order for Game Center to work, your app needs to be registered on iTunes Connect with the appropriate app ID. Even for the simulator. This is counter-intuitive if you are used to App Store development, because normally you don’t have to go to iTunes Connect to register your app until you’re (almost) ready to go and submit it. For Game Center, you need to register it first. If you don’t, GKTurnBasedMatchmakerViewController will just come up looking all empty and dysfunctional.

  • As best as i can tell, you must specify “gamekit” in the UIRequiredDeviceCapabilities section of your Info.plist file for things to work properly.

  • Finally, and most importantly, notifications do not work in the Simulator. If you worked with Push Notifications before, this might not come as much of a surprise, but realize that callbacks such as handleTurnEventForMatch() … will never, ever be called on the Simulator — which seriously will impact how you test game interaction. (In essence, i found the only way to work around this was to manually invoke the GKTurnBasedMatchmakerViewController and re-select the active game to trigger the app to reload the game data and detect the changed game state.)

The Game Board

The second piece of interest in the game is the Board class, which implements all the UI of the game as a really simply UIControl descendant.

The implementation is fairly straight-forward; the class maintains a 3×3 array to keep track of which player has claimed a particular spot on the game board, and in which move (by keeping track of the move number, the game can show different versions of their “X” and “O” markers, making the board look more dynamic).

The begin/continue/endTrackingWithTouch() withEvent() methods are overridden to keep track of — you guessed it — the user’s finger, and they use animations to fade the user’s game piece in and out, and to move it to the next appropriate spot, as the finger moves. (You’ll notice that while the user can move their finger all over the board, the game piece will always “snap” to a fixed position in the closest matching grid spot with a smooth animation.)

All the game pieces (the grid, the “X” and “O” game pieces, etc.) are pre-created images, and the game pieces come in 5 versions (since 5 is the maximum number of moves any one player can make).

The entire Board class is really straightforward and there isn’t much worth covering here that won’t be clear from looking at the code. Worth pointing out is the makeComputerMove method, which invokes Jeremy’s mean ComputerPlayer class, which is used when not playing in Game Center mode.

Tic Tac Toe Board

Summary

I think that’s it (and it’s probably enough ;). Make sure to check out the code on GitHub, and let me know what you think!

Oh, and: even though the code is written in Oxygene, as are the code snippets here, i hope the general description of how to work with GameKit will also be useful to “regular” Cocoa developers using Objective-C. Another nice thing about Oxygene working directly against the standard Cocoa APIs without any abstractions!

Profile photo of marc

by marc

Custom iOS Controls in Oxygene “Nougat”

February 22, 2013 in Cocoa, Elements, iOS, Nougat, Oxygene, Visual Studio, Xcode

A week or so back, Yari D’areglia had an excellent tutorial on his blog on How to build a custom control in iOS that gave a nice rundown of some of the tasks involved, including handling touches, drawing some non-trivial custom UI, and returning events to the application via the target/action pattern.

While Oxygene “Nougat” can of course use any such controls directly and without having to convert or wrap them, i thought it would be fun to try and port the code over to Nougat and see what it looks like (and what kind, if any, challenges would be involved).

We don’t have Oxidizer support for Objective-C yet, so i did this manually, but it was still a very straight-forward process, and below are a few notes:

  • It turns out the new “Auto-Fix” for = vs. := assignments that we are shipping in the February release (which RTMs today) is a huge time saver. Just leave all the “=” in place, and the compiler will fix them for you when you hit build. This is new since i last converted code a few weeks back, and a much appreciated improvement.

  • There’s really only two “repetitive” tasks i found myself doing a lot to convert Obj-C to pascal: (a) changing Objective-C style “[]” method calls to use regular Oxygene “.” or “:” operators and (b) replacing type names with “var” in local variable declarations, such as CGpoint centerPoint = … to simply var centerPoint….

  • There were a couple of C macros used in the original code, which translated nicely into inline methods — a new feature in the Oxygene language for version 6.0.

All in all, i spent maybe 30 minutes last night converting and then tweaking/cleaning the code, and then the control and surrounding sample app was working perfectly (i also found a couple of new compiler bugs — remember Nougat is still beta — which always makes Carlo happy. When i woke up this morning, they were already fixed ;).

 

If you’re at all interested in creating your own controls for iOS (whether in Nougat or in Objective-C), i recommend to check out Yari D’areglia’s post. His original code can be found on GitHub, as can be my ported version.

 

Screenshot

Profile photo of marc

by marc

Using Instruments with Oxygene to Profile your Mac and iOS Apps

January 14, 2013 in Elements, iOS, Mac, Nougat, Visual Studio, Xcode

One of the coolest tools in Apple’s Xcode tool chain is Instruments, the profiler.

Profiling is an essential debugging tool for every developer, whether you want to tune the performance of a particularly time-sensitive piece of code, or drill into some memory issues (be it leaks or general memory load). With ARC, just like with Garbage Collection on .NET or Java, regular object leaks are rare, but one scenario where they can still happen (opposed to GC) is with so-called “retain cycles” — where object A holds on to object B, and vice versa.

Because Instruments is such an essential tool for the Cocoa developer, we have deeply integrated support for it into the Oxygene “Nougat” tool chain as well, and i’d like to demonstrate that in a quick (only somewhat contrived) sample.

Let’s say you have the following code:

type
  DummyData = class
  private
    fData: NSMutableArray;
  public
    method init: id; override;
    method Work; empty;
  end;
 
  DummyDataItem = class
  private
    fOwner: DummyData;
  public
    property owner: DummyData read fOwner;
    method initWithOwner(aOwner: DummyData): id;
  end;
 
implementation
 
method DummyData.init: id;
begin
  self := inherited init;
  if assigned(self) then begin
    fData := new NSMutableArray;
    for i: Int32 := 0 to 1000 do
      fData.addObject(new DummyDataItem withOwner(self));
leak
  end;
  result := self;
end;
 
method DummyDataItem.initWithOwner(aOwner: DummyData): id;
begin
  self := inherited init;
  if assigned(self) then begin
    fOwner := aOwner;
  end;
  result := self;
end;

Looks innocent enough. DummyData holds an array of DummyDataItems it initializes on creation; the code (naïvely) assumes the array and everything else to be released when the DummyData object itself goes out of scope.

Except it doesn’t, and your customer calls to complain that the app’s memory footprint is growing. How do you find out what’s going on? Instruments to the rescue.

In Oyxgene “Nougat” (as of BETA 3), Instruments is available right from inside Visual Studio. We’ve added a new menu item to the Debug menu (and you can also add it to the toolbar of course): Start With Instruments:

Hit that and Oxygene will build your app (if necessary), and via the magic of CrossBox, you’ll see Instruments popping up, Mac side — by default asking you what kind of analysis you want to perform:

Select Leaks and that will open an Instruments document, and also start your application running. Play around with the app and trigger the code paths that lead to the memory increase. In the Instruments window, you san see what’s happening, live — the overall memory load of the app keeps increasing (as shown in the Allocations instrument):

Quitting the app and selecting the Leaks instrument shows all the memory that was leaked — that is, not properly released. The picture is quite clear — it seems that 31 DummyData instances were created and never properly released. What’s up with that? After all, your code that creates DummyData is dead simple:

method MainWindowController.buttonClick(aSender: id);
begin
  var d := new DummyData;
  d.Work();
end;

“d” goes out of scope right after it’s used, and that should release the object, right?

Fold open one of the DummyData items in the list and click on the little arrow next to its address to drill into its retain/release history. You’ll see a huge list of roughly a thousand calls to retain. The call stack on the right tells you these happen from within “DummyDataItem.initWithOwner:”. That makes sense — your code creates a thousand of them, after all.

At the very end of the list, you see that from “buttonClick” your DummyData is being released though.

What’s going on? Shouldn’t “d” going out of scope release the array, which in turn releases the DummyDataItems, which in turn… wait, we’re getting close to the problem! It looks like our data structure contains what is called a “retain cycle”. The DummyData holds on to the NSArray, which holds on to the DummyDataItems which, in turn, hold on to the DummyData itself. Even though “d” is going out of scope, its retain count is only going down to 1001, because all the DummyDataItems still have references. As a result, the DummyData object actually never gets freed, and neither does the NSArray or the DummyDataItems inside it, which, in turn, can never give up their hold on the DummyData itself.

Though in this case we found the issue fairly quickly, Instruments has one more tool up its sleeve to make it even easier to find retain cycles: Click on the Leaks item in the navigation bar and select Cycles & Roots:

Instruments has actually detected any retain cycles for us and shows them in a list (in this case, 31 of the same), along with a nice graphical representation of what is going on.

From this view (even without our previous investigation), it becomes immediately clear that the fOwner reference from DummyDataItem back to DummyData is the culprit.

How do you break this vicious circle (assuming you cannot simply drop the owner reference altogether)? Weak references to the rescue!

type
  DummyDataItem = class
  private
    fOwner: weak DummyData;

By default, all variables and fields in Oxygene (and Objective-C with ARC) are strong — that means when an object is stored in the variable, its retain count is increased. By contrast, weak references just store the object, without affecting retain count. In fact, they do one better: they also keep track of the referenced object and automatically get set to nil when said object is released — so you never have to worry about the variable pointing to a stale object (which is a big problem in non-ARC languages).

Sidebar: A third type of object references are so-called unretained references. These behave like regular pointers in old-school languages; they store the object address, and when the object gets released that address will be stale — your code will be responsible for worrying about that.

With the code fixed, hit the Start With Instruments menu again. Your app will launch and Instruments will profile, and as you work with your app, you will notice that the memory load now stays down — as originally expected.

Of course, the Leaks pane will remain empty, but just to confirm, you can select the Allocations instrument, select Created & Destroyed in the sidebar and then locate and drill into one of the DummyData objects. As you can see, the retain/release history is much more sane now — no 1000 extra retains from DummyDataItem — and the object actually was released at the end of “buttonClick”.

Success!

 

So what have we seen in this article? We’ve had a quick look at how Instruments works and can be used to inspect memory allocations (the first phase of the investigation above does not just apply to bona-fide leaks and retain cycles, but can also be helpful if you just want to get a general impression of what memory your app is holding on to, and why), learned about retain cycles and strong, weak and unretained object references and we have also seen how Instruments can be used from Oxygene Nougat (which was so dead simple, it hardly warranted mentioning, wasn’t it?).

Profile photo of marc

by marc

Working with User Interface files in Oxygene “Nougat”

January 2, 2013 in Cocoa, Elements, iOS, Mac, Nougat, Oxygene, Visual Studio, Xcode

In this article, i want to talk a bit about working with user interfaces in Oxygene Nougat.

As you know, Nougat is a native compiler for the Objective-C runtime, meaning that it works directly with the classes provided by Apple’s Cocoa and Cocoa Touch frameworks. This extends from low-level classes such as NSString or NSArray to the high-level visual components based around NSView (Mac) and UIView (iOS).

One common way for Mac and (especially) iOS apps to work with UI is to simply create the necessary views and controls that make up an app’s UI from code. But sooner or later, especially when dealing with more complex or sophisticated user interfaces, you will want to use the visual designer. This works on the same principles, whether you are using Xcode/Objective-C or Nougat.

Mac and iOS interfaces are designed in Interface Builder, which as of version 4 is directly integrated into the Xcode IDE, and when working with Nougat, that is where you will work with your interfaces, getting the same experience and the same power and flexibility of UI design that developers using Objective-C get, as well.

There are two file formats used for designing UI on Apple’s platform — the older XIB format and the newer (and iOS-only) storyboard format. The principles for dealing with these files are similar, but for the topic of this article, we’ll focus on XIB files, as those apply to both Mac and iOS development. In a future article, i will go into some more details specific to storyboards.

Background: What are XIB Files?

So what are XIB files? From the point of view of the UI designer, XIB files contain the views or windows that you design in Interface Builder — the controls, their layout and properties, and their connections to your code.

It is important to understand that on a technical level, XIB files are stored object graphs. That means that an XIB file, essentially, is a hierarchical set of objects descriptions. When an XIB file gets loaded at runtime, all the objects defined in the XIB file get instantiated, configured, and connected as described in the XIB.

These objects can be a combination of standard framework classes (such as NSView/UIView, NSButton/UIButton, etc), classes from third party libraries, or even classes defined in your own application code. When the Cocoa runtime loads an XIB, it goes thru the list one by one, looks for the classes with the appropriate names and news up the necessary objects.

Each XIB file also knows about a special object called the “File’s Owner”. This object will not be created when the XIB is loaded. Rather, the object that initiated the loading of the XIB file will take the place of the File’s Owner within the XIB’s object graph — including any connections and references to it. We will see how that is useful and important, soon.

Loading up an XIB

When and how do XIB files (or storyboards) get loaded? There are several possibilities:

 

NSMainNibFile

If your Info.plist contains an NSMainNibFile entry, the Cocoa runtime will automatically load up that XIB as your application starts up. The global NSApplication/UIApplication instance will become File’s Owner of the XIB, and every object in your XIB will be instantiated.

This mode is common for Mac applications, and in fact you can see it in action in our Cocoa Application template(s). You probably noticed that (aside from the startup code in Program.pas) the project contains an AppDelegate class that is usually used as the “launching point” for your application’s own code.

How does this AppDelegate class get instantiated? Easy: If you own the MainMenu.xib file in Xcode (the xib that is specified to be the NSMainNibFile in Info.plist), you see that — among other elements — it contains an AppDelegate item. This is your own AppDelegate class.

initWithNib:*

For simple applications, you can get away with just putting all your stuff into MainMenu.xib, but as applications get more complex, that’s a bad idea, not only because — as indicated above — when an XIB is loaded, all objects referenced in it are created. If your application contains dozens of windows or views, you don’t usually want all of those to be loaded up as your application starts.

Instead, it is common practice to pair individual XIBs for each view or window XIB with a matching ViewController or WindowController class — a practice that you will see in just about all the iOS project templates, and also in the *Controller item templates we provide with Nougat.

How does this work?

Simple: your application will define a custom class, usually descended from UIViewController (or NSViewController/NSWindowController) where you will put all the application logic for that view or window. As far as your app is concerned, this class is your implementation for that particular view (or window — for simplicity reasons i’ll stick to talking about iOS Views for now, but the same concepts apply for OS X views and windows).

In the initializer for your view controller, you will ask the base class to load up the XIB file that backs your view, for example by calling

self := inherited initWithNib('MyViewController') bundle(nil);

This essentially tells the base class to initialize it by loading MyViewController.xib (from the main application bundle) and creating all the objects defined in it.

So all those objects get loaded up, but how do you then get access to them from your code? Simple: remember when i said above that the object loading the XIB becomes the File’s Owner? When you load an XIB using the initWithNib() call, your view controller class becomes the File’s Owner — and any connections you set up in the XIB between the File’s Owner and the other elements in your XIB will be connected to your view controller class.

Connections

Did i say connections? So how does this work?

Easy, really. XIB files know about two basic kinds of connections between objects: Outlets and Actions.

You can think of outlets as references to other objects. If your view controller class has a property of type UIButton, and your XIB file contains a UIButton, that’s a match made in heaven. You can just Ctrl-drag the button onto the File’s Owner (or vice versa) in the XIB to hook them up, and now you have access to the UIButton from your code, because as the XIB gets loaded and the UIButton gets created, it gets hooked up to your property automatically.

Actions, you may have guessed, can be thought of as events. If something happens with the objects in the XIB (such as a button being tapped), they send out events. Just as above, if your view controller exposes a method with the right signature (that is, any method with exactly one parameter of type “id” or a concrete class), you can Ctrl-drag it into your XIB file to hook them up — and when the event triggers, that method is called.

Of course outlets and actions can be hooked up between any two objects inside your XIB, not just with the view controller. For example, you can cause an action on one control to trigger a method on a different control.

Ok, so how does the XIB designer in Xcode know about the methods and properties on your view controller (or other classes)? Magic! As you write your classes, Nougat will automatically* update the XIB and Storyboard files, behind the scenes, with information about all the relevant classes and their properties and methods — that is any property marked “[IBOutlet]” and any method marked “[IBAction]“. As you work on your XIB file in Xcode, it sees this information, and makes the connections available.

If you need to expose a new control to your code or want to hook up a new event, simply add a new property or method to your code, and that’s it.

Let Me See This in Action

For this example, i’ve created a new “UIViewController with XIB” from the template. I have then added the following items to the “MyViewController” class:

property myButton: UIButton;
property myLabel: UILabel;
method buttonTapped(aSender: id);

The following screenshot explores the XIB (and storybook) designer in Xcode:

Figure 1: On the left side of the window, you see a hierarchical view of all the objects in the XIB — this includes all visual objects (in this case just the one UIView for now, but also other objects such as the File’s Owner).

On the right side, the “Utilities View” has the “Identity Inspector” pane activated, showing details about the selected object (the File’s Owner). Note that the XIB designer knows that File’s Owner is a “MyViewController”. It got that information from the template – but this is editable, so you can just type in or select the right class name. Of course it should match the class that is loading this XIB at runtime.

Figure 1

Figure 2: We have dropped a couple of controls onto the view — you can see them both visually and in the hierarchy on the left. The right pane has been switched over to the “Connections Inspector” tab, which shows all the connections available on our File’s Owner. Among them, you see our two properties and the method. There’s also a “view” property (defined by the UIViewController base class), already connected to the root view.

Figure 2

Figure 3: Click and drag from the little circle right of the “myButton” name to the button to make a connection to the UIButton. (You can drag to the control on the design surface or to the “Button — Tap Me!” item in the hierarchy.)

Let go when you are over the button, and the connection is made. If you were to go and build your app now, the myButton property would give you access to the button from code.

Figure 3

Figure 4: You can also drag from the hierarchy view to a control. When you let go, the XIB designer will present a list of all properties that match — in this case the UILabel qualifies both for “myLabel”, and for the “view” property (because UILabel descends from UIView).

Figure 4

Figure 5: Connection actions work the same way. You can Ctrl-drag from the control to the receiver (here the File’s Owner) to connect the default action of that control (in this case, the button tap) to a method. As you can see, the Connections Inspector also shows a complete list of all actions that can originate from the control, so you can — if needed — assign them all to individual methods.

Figure 5

Now all that’s left to do is maybe write an implementation for “buttonTapped” such as this:

method MyViewController.buttonTapped(aSender: id);
begin
  myLabel.text := myButton.titleLabel.text;
end;

to see both actions and outlet access in — pun not intended — action.

Terminology: XIB vs. NIB?

In the text above, i talk about XIB files, but the method names all mention NIBs. What’s up with that?

XIBs are a newer, XML based format that is used for the UI at design time. When you compile your app, the XIB files are converted to binary NIB files for you, and those binary versions of the files are embedded into your app. All the APIs working with these files predate the new format (and, at runtime, only work with the older NIB format), that’s why all the method names refer to NIB, not XIB. When you pass around names, you never need to (or should) specify the file extension anyway, so this is a distinction that you can largely ignore (unless you want to go spelunking into your .app bundle).

What’s “First Responder”?

Similar to File’s Owner, “First Responder” is another placeholder object exposed in the XIB file that has special meaning. The First Responder is not a concrete object, but essentially refers to “the first object that has focus that can handle this”.

By connecting actions to the First Responder, you can have them dynamically be sent to different parts of your application, depending on the state your app is in. A good example is the “Edit|Copy” menu in a Mac application. If a text field has focus, you would expect the Copy command to apply to the content of that text field. If a different control has focus, different content would be copied. By connecting the menu’s action to the First Responder’s “copy:” method, Cocoa will take care of calling “copy()” on whatever control or view has focus — in fact, all you need to do to make Copy/Paste work with your own custom view would be to implement the corresponding methods, and they would get called if your view has focus as the user invoked the menu item (or Cmd-C keyboard shortcut).

Summary

I hope this gave you a quick introduction to XIB files and how they work. A good 95% of the content of this article is not really specific to Nougat; the same concepts and techniques apply to working on XIB files with Objective-C — that’s by design, because Nougat is a true first class citizen on the Cocoa frameworks and Objective-C runtime.

Footnotes

(* in the current beta drop, this update does not happen automatically yet. You can right-click your .XIB or .storyboard file in Solution Explorer and choose the “Sync XIB”/”Sync Storyboard” to trigger an update.)

Profile photo of marc

by marc

Using RemObjects SDK and Data Abstract with Oxygene Nougat.

December 25, 2012 in Cocoa, Data Abstract, iOS, Mac, Nougat, Oxygene, Visual Studio, Xcode

Nougat is, of course, designed to work with any existing Objective-C libraries out there, because it directly consumes and generates code for the Objective-C runtime. As such, it should come as no surprise that Nougat is ready to use RemObjects SDK and Data Abstract for Xcode, out of the box.

That said, with the new Alpha builds of RemObjects SDK and Data Abstract that we shipped on friday (build .1069), we have made a few improvements that make it even easier to get started with RO/DA in Nougat. These are three-fold:

Read-to-Use .fx files

Unlike .NET and Java, Cocoa libraries do not include easy to parse metadata for compilers to consume. Instead, it depends on .h files to define the available APIs — which is fine when consuming the libraries from a C compiler. Because .h files are slow and complicated to parse, Nougat introduces an intermediary format in the form of .fx files. You can think of an .fx file as “pre-compiled headers” file for a given framework or library; a set of metadata that represents all the information expressed in the framework’s .h files, but encoded in a way that it is easy and quick for the Oxygene compiler (and IDE toolchain) to process, when compiling, driving Code Completion etc.

While Nougat comes with the necessary tools to generate .fx files for any of your favorite third party libraries (and of course ships with .fx files for the supported base SDKs), that is an extra step we want to alleviate, so the new build of RODA/Xcode includes .fx file for those libraries out of the box. After installation, you will find the files next to the corresponding binaries in ./Bin.

All you need to do to use the SDK or Data Abstract from Nougat is to go to “Add Reference”, select the .fx file for your platform (i.e. OS X or iOS) to add a reference. That’s it.

libDA.fx Reference

From the .fx, Nougat will automatically know about all the types in the RO/DA library, and will take care of getting the static library and any dependencies linked in.

Static Libraries for OS X

In the past, RODA/Xcode included precompiled binaries in the form of a framework for OS X and static libraries for iOS. Frameworks are easier to deal with in Xcode, because they combine a binary with its accompanying header files, which is why we chose to ship OS X binaries as a framework. iOS does not support the framework format for third party libraries, so the choice there was easy: static libraries are the only option.

For Nougat, the benefits of a framework (on OS X) are diminished, because metadata is provided in the .fx file anyways, so a static library is just as easy to deal with, and has fewer files involved. For that reason, we have added a static library version of RODA/OS X to the product (in addition to the Framework). Xcode developers can choose to use either version, depending on their preferences (the static library has the benefit of being linkable straight into the executable, which is nice if you’re creating command line tools that use RO/DA); Nougat developers will mostly want to use the new static library alongside its .fx file.

CodeGen for Nougat

For pure Data Abstract use, you’re pretty much all set with the above, but if you’re building custom RemObjects SDK services that you want to talk to, there’s one more step missing: Interface code.

Talking to RO services depends on having strongly typed interfaces generated for your local proxy classes and any complex types you are passing back and forth between the client and the server — and until last week, RO/Xcode generated this code in Objective-C only.

That was not a complete showstopper for Nougat. Remember, Nougat can use any Objective-C library, so you could compile those files using Xcode and the use them from Nougat (in fact, that’s what i’ve been doing with for small RODA project i have been working on over the past few weeks). But that’s not ideal, of course.

The new alpha now includes native Nougat CodeGen for your services, so you can generate an Interface .pas file and add it straight to your Nougat project — as it should be.

The new CodeGen is exposed in three places:

  1. Of course the codegen2.exe command line utility has been updated, so if you generate code from the command line, you can use the /lang:nougat option to have interface files written for Nougat.

  2. Service Builder has also been expanded to support Nougat alongside all the other languages (that menu is getting mighty big!):

Service Builder

  1. Finally, we also added Nougat CodeGen to our rodl2objc.app on the Mac (which is now really becoming overdue for a rename ;). While we were at it, we also revamped the UI for this tool a bit to make it (simple as it is) nicer to use, and look at:

rodl2objc

(and as the beta progresses, CodeGen will also be available directly inside the Visual Studio IDE, as well)

So with that you should be all set to build your first great client application for the Mac or iOS, using RemObjects SDK/Data Abstract and Oxygene “Nougat” over the holidays ;)

Let us know how it all works out!

yours,
marc

Profile photo of marc

by marc

What is “Nougat”? — Part 4

October 19, 2012 in Elements, iOS, Mac, Nougat, Oxygene, Uncategorized, Visual Studio, Xcode

In the first three parts of this series, we took a look at the basic concepts and design principles behind Oxygene “Nougat”, and the IDE experience. In this fourth installment, i’d like to give you an overview of the build and deploy process, and a quick peek at debugging.

Building your project is something that happens behind the scenes and most of the time, we don’t think much of it. We press F5 in the IDE, and a few seconds later our app is running. But a lot is going on behind the scenes to get from your source code to the final executable — and a lot more than usual, for building Mac and iOS apps.

Let’s have a look. All that we’ll be seeing here happens, of course, behind the scenes and automatically, without you having to worry about a thing.

It all starts with the Oxygene compiler, which takes your source files and turns them into executable code. For Nougat, that is the same Oxygene compiler you know and love, only instead of emitting a final “.exe” or “.jar” file as it would do for .NET or Java, it generates a file with CPU-native binary code for either x64 or armv7(s), and a “.o”. (In fact, if you’re building an iOS app with armv7 and armv7s support, the latter being new for the iPhone 5, it will generate two such files.)

On the back-end, Oxygene leverages the great LLVM compiler, which generates highly efficient code.

The “.o” is not the final executable, it still has to be linked. So next, our toolchain calls “ld”, which is the linker. This happens via CrossBox, passing the “.o” file over to the Mac, linking it against all the frameworks it needs, and returning the final executable (which is extension-less) back.

At this stage, we’re done if we’re building a Mac console app, that is, a simple executable that you want to run from the command line. Most Mac (and all iOS) apps aren’t simple console apps, so there’s more that needs to be done to get a final, runnable app — and Nougat does that for you, of course.

Mac and iOS apps come as what is called “Bundles” — which are really folders with an .app extension that are treated as individual files by the OS X finder and other parts of the OS. In the Project Properties of your Nougat app, you’ll find a checkbox called “Create .app Bundle” (checked by default in most templates) that enables this functionality:



With the option set, Nougat’s build chain will take the executable generated above, along with any other files your app needs (such as images or other resources) and generates a full .app bundle. It will also automatically generate an Info.plist file describing your app, or take an existing Info.plist file that’s part of your project and adjust/tweak it as necessary.

The Info.plist file, next to the executable, is an important part of the .app bundle that tells the OS how to run our app, what documents it supports, what application icon to use, etc.

If you’re building a Mac app application, you can be done at this point, and the resting .app bundle is fully runnable. However, these days it’s good practice to digitally sign your application (and in fact that’s required for iOS apps, and also for Mac apps if you want to use the Mac App Store).

How do you sign your app? Nothing easier than that. Looking at the Project Properties again, there’s an option called “Code signing certificate name”, along with a drop down that shows you all the (relevant) certificates Nougat found on your Mac that can be used for signing apps (this list will differ between Mac and iOS projects). Simply select the right certificate, and when you build, Nougat will automatically code-sign the final .app bundle for you.



For iOS apps you will usually choose a “iPhone Distribution: XXX” or “iPhone Developer: XXX” certificate issued by Apple, where XXX is your name or your company name. Distribution certificates are used to build apps to ship on the app store or deploy to beta testers or inside your company; Developer certificates are used while you’re testing your apps on your own devices.

For the Mac, you can choose between “3rd Party Mac Developer Application: XXX” certificates for deployment of Mac App Store apps, or you can use Apple’s new “Developer ID Application” certificates, for non-MAS apps.

In either case, all you need to do is select the certificate, and off you go.

iOS applications also need what is called a “provisioning profile”, generated on Apple’s developer portal, to govern how they can be run. As you might have guessed, there’s an option in Project Properties that lets you pick the provisioning profile you want to use from a list, and Nougat takes care of the rest.

The actual code signing, once again, happens on the Mac, marshaled over transparently via CrossBox, so you don’t even notice it’s happening.

There’s a few more things that might have to be done as part of this process (for example .xib and .storyboard files that might be part of your project will get post-processed into a binary format before being included in your .app bundle), but finally, we have a finished .app bundle that’s ready to be used — run, debugged or, hopefully at some stage, be submitted to the App Store.

Running and Debugging also happens seamlessly. In the CrossBox menu we already saw in my previous post, you can select a Mac or a Device (real or virtual) connected to your Mac:



The menu will list any Mac on the network that’s running CrossBox, as well as any remote CrossBox server you might have connected to. Underneath each Mac, you can select the device you are building for and deploying/running/debugging on. For Mac OS X applications that is just the Mac itself, but for iOS, you can choose between the “iOS Simuator”, a generic “iOS Device” (which lets you build for a device seven without having a real one attached), as well as any actual devices connected to your Mac:

For iOS, the selection you make here affects several parts of the build process. First of all, the Mac you select is of course the one that will be used for all tasks that need to be handled Mac side (linking, code signing, etc).

More importantly, by either choosing “iOS Simulator” or a device (whether a real one or the generic “iOS Device”), you are telling Nougat whether to build your project for device hardware (i.e. in most cases armv7 and armv7s binary, and against the real iOS SDK) or for the Simulator (in which case it will generate an i386 binary, linked against a separate Simulator version of the SDK).

Finally, the device choice also influences how your finished application runs. If you selected a real device, Nougat will deploy the .app to that device, and optionally launch it there, to run or be debugged, and if you selected the iOS Simulator, the app will launch in the simulator on the Mac. (Obviously, an app cannot be deployed or run on the generic “iOS Device”, that option is for building the app only.)

Debugging the application is almost unspectacular, in spite of a lot of effort having gone (and continuing to go) into this: Nougat adds a full Mac and iOS debugging engine into Visual Studio, based on the LLDB debugger, allowing you to use virtually all of the capabilities of the Visual Studio debugger that you are used to from .NET (and Java — where we did the same). You’ll be using the debugger as you always have:

Summary

Ok, so this post took you on a quick tour on what happens behind the scenes when you press “Start” to build and run your Mac or iOS project.

In hindsight, there’s a lot happening, but none of it is any black magic. Nougat takes care of all the gory details for you, so you don’t have to worry about provisioning profiles, code signing and the like, but it will document all the steps it takes (and any command line tools it runs) in the MSBuild log, so that there’s no “black box” and you can know what’s going on, if you care.

Reminder: Keep in mind that the Nougat beta is active now (we started last Monday), so if you pre-ordered the Oxygene 5.2 bundle or own a Suite Subscription for Xcode (we’ll have to rename that one, won’t we?), you have access to the beta now. If you didn’t — well, what are you waiting for? Order your copy now!

Stay tuned for more.

Profile photo of marc

by marc

Comparing Data Abstract and Core Data (with and without iCloud)

August 6, 2012 in Data Abstract, iOS, Relativity, Xcode

People often ask us what the difference between Core Data and Data Abstract is, and why they should choose one over the other.

The answer to that second question frequently is “it depends”, because while on first glance Core Data and Data Abstract might seem like technologies that solve the same problem (“database access”), they are actually quite different technologies, and designed with very different goals.

Core Data is, in essence, a local data access technology and ORM. It is designed around the concept that your application has a certain data model, expressed as a suite of objects, and wants to persist that data between runs (or to save runtime memory footprint), locally. As such, Core Data is largely a front-end for SQLite (although it supports other storage options) that abstracts the developer from dealing with the actual database storage, table structure, and SQL queries, and exposes data as regular in-memory objects that magically persist.

Don’t get us wrong, that is an awesome feature for many scenarios, and Core Data is a great solution in that space.

Data Abstract on the other hand is designed around the concept of data stored on a “big” server somewhere on the network, off your iDevice or Mac, or “in the cloud”, and that the database on this server (or these servers) contains data that is shared between many users of the application (which of course does not mean that each user cannot have their own private set of data).

These servers could be anything, from an existing database in a large Oracle cluster that already provides the backbone for an enterprise, to a fresh database you just designed solely for your iOS app. The target application could be anything from — say — a view into said enterprise’s customer relations system, over an iOS front-end to your web site, to the client app for the next Social Network you are building.

To achieve this, Data Abstract is build around the so-called Multi-Tier concept, where the client applications you build using Data Abstract talk to a “middle tier” server that enforces data consistency and access restrictions.

 

The central difference between Core Data and Data Abstract is that the former is focused around simplifying how an app can persist its application state locally, while the latter is designed around accessing, presenting and working with data that exists elsewhere, usually (but not necessarily) in a context that is much larger than an individual application and an individual user.

So Core Data and Data Abstract aren’t really that much in competition, but target pretty different scenarios. In most cases where Core Data is a good solution, Data Abstract would be overkill or even useless, and in the cases where you need what Data Abstract provides, Core Data won’t do much good.

But What About Core Data in iCloud?

On first glimpse, it might seem as if the new Core Data Syncing via iCloud expands Core Data onto Data Abstract’s turf. And to a certain degree that is true; iCloud certainly expands what you can do with Core Data, but there are still some pretty severe limitations.

When Steve Jobs took the stage at WWDC in 2011 to announce iCloud, he gave the reason why iCloud was going to be better than previous syncing technologies: Rather than syncing information between devices he said that with iCloud the “truth, is in the cloud”, and each device — iOS or Mac — syncs against a well-known set of data in that single location.

That is the right way to do it, and that is how iCloud works in general, but: it is not how Core Data syncing via iCloud works, unfortunately.

At the time of this writing, Core Data syncing via iCloud consists of each client storing change logs in the cloud and these diffs getting transferred between devices. In other words, iCloud syncs Core Data between devices, without a single truth “in the cloud”. As Drew McCormack has outlined in his excellent series of articles on the topic, this comes with a myriad of problems, caveats and corner cases to look out for.

This is, of course, in sharp contrast to how data access with a multi-tier solution such as Data Abstract is handled. Data Abstract’s model (or any other database-centric multi-tier architecture) does put the truth in the cloud, just as Steve Jobs suggested it should be.

Another crucial limitation of Core Data is that any data it stores in iCloud is still an island: it can only be accessed by the applications that created it, and is isolated per user. That is fine for many scenarios (e.g. in cases where you’re 100% focused on in-app presentation), but imposes some serious limitations, such as:

  • not being able to provide a web-based front-end to user’s data outside of their iOS apps.
  • not being able to provide access to the user’s data on iOS/Mac on the one side, and client applications on other platforms (be it Android, Windows, or even just non-App Store Mac) on the other.
  • not being able to offer options for users to share data among themselves, or share data publicly.

Also, the fact that data is self-contained within each user’s store means that as the application developer, you have no access to it, for example to investigate if users are reporting problems. On the one hand, this is a win for user privacy, as users only need to trust Apple with their data, not you as the App Vendor, but on the other, it severely limits what apps can do and how you as an app developer can trouble-shoot or assist users when they have problems with their data.

So, Which Option Should You Choose?

Indicators that Core Data is the right solution would be:

  • You have a fairly straightforward data model and not more data than can easily it on the device.
  • Your data is internal to the application, and you never want to use it outside of the app (aside from, say, letting the user explicitly export it).
  • Your entire data is tied to a single user and you have no need to share (part of) the data between different users of your app.

Indicators that you might want to use Data Abstract include:

  • You are building a front end to already existing data managed in a database (e.g. an app for your Enterprise database).
  • Your app’s data is part of a larger data infrastructure shared (in parts) by all or some users of your app.
  • Your app’s data should be accessible (in parts) outside of the application itself, for example via a web site.
  • Your app’s data should be available on platforms not covered by iCloud, for example Windows or Android clients.
  • Users of your app should be able to share (parts of) their data, whether explicitly or implicitly.
  • Your application contains shared data common to many or all users.
  • You want or need full control and access to the data and how it is stored.

The one advantage of Core Data, of course, is that it works “out of the box” with just the user’s devices, and (optionally) iCloud, and you do not need to worry about setting and maintaining any database and server yourself.

If your application can live within these constraints, that can be a significant saving in both cost and management effort. But in most cases, you either need the extra flexibility of hosting the data yourself, or you don’t — and if you do, Core Data and iCloud give you absolutely no wiggle room and hosting your own data will be the only solution.

Data Abstract makes that easy and cost efficient too, and with our free Relativity Server that can be hosted on just about any co-located server and on many cloud services, such as Amazon EC2, you can be up and running with your own hosted middle-tier quickly.

Interested?

If this got you interested, please check out some of our other resources on Data Abstract for Xcode (and for our other platforms) to see what DA can do for you and how to get started.

In particular, i recommend reading the first available chapters of our “Data Abstract for Xcode Book” and to check out the videos on RemObjects TV, especially Introduction to Data Abstract for Xcode narrated by yours truly and Relativity Server Overview.

And of course we have a free 30-day trial versions of Data Abstract for all platforms.

We hope you will find Data Abstract useful — and don’t hesitate to contact me directly or our support team if you have any questions.

— marc