Xml parsing and serialization for Mac OS X and iPhone OS

Wednesday, June 10th, 2009 | Programming, iPhone | 4 Comments

Apple provides the NSArchiver and NSUnachriver for object serialization / deserialization, but this can not handle any custom xml schema. So filling an object structure with the data of any custom xml schema has to be made manually. Since the iPhone developer community is rapidly growing, a lot of newbie programmer are despairing to deal with the available xml parsing possibilities.

The iPhone SDK only provides NSXmlParser for xml parsing, which is more useful to read certain parts of an xml file, than filling a whole object structure, which really is a pain.

The other possibility is the famous libxml library, which is written in ANSI C - not easy to use for someone who starts programming with objective-c and never learned proper C before. Event there are a lot of wrappers available, dealing with xml can be a pain for newbies.

And here my idea takes place. An XmlSerializer library which fills an object structure automatically could makes it a lot easier and increase the app quality for many programmers. My Idea should work like this:

The xml file:

<Test name="Michael" uid="28">
    <Adress street="AlphaBetaGammastrasse 1" city="Zürich" postCode="8000" />

  <Hobbies>
    <Hobby describtion="blabla"/>
    <Hobby describtion="blupblup"/>
  </Hobbies>
</Test>

The business objects:

@interface Test : NSObject {
    NSString *name;
    Adress *adress;
    NSArray *hobbies;
    int uid;
}
@property (nonatomic, copy) NSString *name;
@property (nonatomic, retain) Adress *adress;
@property (nonatomic, retain) NSArray *hobbies;
@property (nonatomic, readwrite) int uid;
@end

@interface Adress : NSObject {
    NSString *street;
    NSString *city;
    int postCode;
}
@property (nonatomic, copy) NSString *street;
@property (nonatomic, copy) NSString *city;
@property (nonatomic, readwrite) int postCode;
@end

How the xml serializer should work:

XMLSerializer *serializer = [[XMLSerializer alloc] init];
NSData *data = [NSData dataWithContentsOfFile:@"~/Documents/Test.xml"];
Test *test = [serializer deserializeWithData:data];

So I started a project for this idea. If you are interested in, the project can be found here. If you would like to join the project, so don’t hesitate to use the provided mailing list and ask for access.

Tags: , , , , ,

Around the Lake of Constance

Wednesday, June 10th, 2009 | Traveling | No Comments

After a quite long non traveling time, we went for a Lake of Constance trip with our bikes on white sunday.

You wont believe it, but we use our bikes the first time since my girlfriend arrived  Switzerland. So we decided to remove the dust and pedal the 210 km around the lake.

Day 1
Starting point was Kreuzlingen. Together with our colleagues we head of across the german border to Constance. This is quite near and we already could enjoy the first sight at the lake.

Lake of Constance

We decided not to take the ferry to Meersburg, but to visit the peninsula Mainau and continue via Ludwigshafen to Meersburg.

It took us about half an hour to arrive at the peninsula Mainau. The entry of 8€ is not that cheap just to visit an island, but we wanted to see something on our trip, so we payed and entered to the paradise of the flowers.

Peninsula Mainau

Peninsula Mainau

Unfortunately a week before has been this thunder storm, which destroyed most of these wonderful flowers, but there where a lot of birds, restaurants and the butterfly house. The butterfly house was very nice, within a tropical winter garden with a lot of nice orchids and flying butterflies in every color.

After a quick Lunch we continued our trip. The way to Ludwigshafen was very hilly, four hours up and down can be very exhausting, so we where glad to pass Ludwigshafen where we made a small break and continued our way in direction Meersburg.
We arrived in Überlingen at  20:00 so quite late and we searched for rooms, but all hotels in and around Überlingen where fully booked out. With pure luck we finally me a guy from a youth hotel, which just got free space, so we immediately grabbed it.

Day 2
In the second Morning, we visited the pile dwelling museum, where they reconstruct several historical pile dwelling villages and show how they lived in these ancient times.

Pile dwelling museum

Pile dwelling museum

Afterwards we arrived in Meersburg, a small city with beautiful old town, where we made a break and discussed our further way. We where very affray that we wont find a room in the second night, because thew day before it was really tight. Finally we decided to drive to Friedrichshafen and take the ferry to Romanshorn, what we did at the end.

The plan was, to driver in direction of Rorschach, if we find a room on the way we’ll stay, otherwise we take the train back home. The pathway to Rorschach is very flat and peaceful. Where the many tourist shops and restaurants have been on the german side, only some fields, forest and a few camping grounds are on the swiss side.
Arbon, somehow, is the swiss counterpart of Meersburg, a small nice city, with a beautiful old town and a castle with the ruins of an ancient roman bath.
And nearby this village we found a small and cheap hotel where we booked our rooms. The hotel just has been renovated and has been clean that you could eat from the floor, very nice.

Day 3
On the third day, we first continued the last 8 km to Rorschach where we made a u-turn and drove back to Romanshorn and afterwards it just has been further 22 km back to Kreuzlingen.
The end of our journey , we enjoyed in Back & Brau in Frauenfeld.

Tags: , ,

NUndoManager project started

Wednesday, May 27th, 2009 | Programming | No Comments

Since I miss the amazing undo manager from Apples Cocoa Framework, I started to implement my own version of an undo manager, using the same recording techniques.

The so called NUndoManager is the first .NET 3.5 undo manager, recording lambda expressions of methods reverting the state of an object. Additionally NUndoManager groups single operations for undoing at once. Reverted undo operations are automatically to the redo stack.

The project is hosted here. Have a look or join the project if you want to add your own ideas.

Tags: , ,

Compiling

Tuesday, May 19th, 2009 | Programming | No Comments

This I found just shorly :)

Tags: , ,

Model view presenter - make your live easier

Monday, March 16th, 2009 | Programming | No Comments

The MVC (Model View Controller) patter is a well known object pattern for GUI abstraction, which is taught on every it school. But many programing language don’t support the programmer to use this pattern from scratch. 

For example Java, or C# .NET  are based on a inheritance topology, the IDE’s create subclasses of the GUI components, resulting in huge source files, which are mixed up with everything. Not to mention that there is no compatibility to other GUI components, e.g. ASP .NET.

Apple with it’s Objective-C / Cocoa framework made a good step in the right direction, the programmer is forced to use the MVC  pattern, since the GUI is described in so called NIB files. A controller class contains the code. The NIB file can theoretically  be changed without changing the controller. 
Also .NET 3.5 has a good answer to this technology, the windows presentation foundation. The GUI is described  in XAML files, which are linked to classes. The XAML file could also be exchanged without changing the source code.

These technologies are based on the MVC patter, which still has a string connection between view and model. Further the controller has direct references to the controls within the view. If we want to change a windows forms view with a ASP .NET view, or change the model, the MVL pattern is not flexible enough. This is where the MVP pattern starts to unfold its strength.

The MVP, or more precisely the passive model view pattern is based on three simple interfaces; Model, View and Presenter. View and model are independent entities, only the presenter links the three parts together.

Passive Model View Presenter pattern

Passive Model View Presenter pattern

Compared to the MVC pattern, the presenter has no direct connection to the GUI controls of the view and the view does not know the model.
The presenter can observe the view and the model, if any changes happens within the model, the presenter gets notified and tells the view what to do. The same procedure happens, if any user interaction happens on the view; The presenter gets notified and has to handle the interaction.
In this case, we can easy implement the view in ASP .NET, Windows Forms, WPF etc. and run it with the same model and presenter. 

In some cases, we need a container view, which can maintain any sub views. For this, we extend the passive view pattern with a sub view. The presenter of the container only knows the presenter of the sub view. Sub views are added by adding the presenter of the sub view to the presenter of the container view, model and view are not referenced by the container view presenter.
Since the container view needs no know the sub view, the presenter forwards the sub view to its own view. With this MVP pattern and IoC (Inversion of Control) it’s also possible to use different technologies to implement the views with only one restriction: All views need to be compatible among each other.
 

MVP - Sub View

MVP - Sub View

The most nice advantage at all is, that we can use dependency injection to create our object structure. To describe this technology would be beyond the scope of this article, but I can provide you some links:

Microsoft Unity Application Block
Ninject

Tags: , , ,

Thailand the third…

Tuesday, January 27th, 2009 | Traveling | No Comments

Since I met my girlfriend in october 07, we have been in Thailand twice and continuing our tradition, we departed to Bangkok on 26th of december for the third time.
Aye, the cold weather, no sun and almost every day the grey fog over the landscape, as you can imagine, we were really looking forward to the tropical condition in the home of my girlfriend. And we had really a lot of plans in Thailand and only three weeks for executing.

Khon permformance

Khon permformance (image from wikipedia)

In Bangkok, after a small nap, we head of for the traditional khon dance performance in the oldest cinema of Bangkok. Khon dance is the royal dance in thailand, the story is always being told by a chorus at the border of the stage, which is illustrated by the dancers in colorful, handmade cloths and masks. The story is mostly a part of the epos of Ramanaya.
The more important a figure is, the more detailed and beautiful is the dress of the dancer. Demons and monkeys are illustrated with a mask. Every mask is unique and shows the character of the figure. 

After some days of shopping, we head of to the north of Thailand. On the 30th of december, we arrived in Sukhothai, the oldest capital city of Thailand. The hotel was an old, traditional thai house with a pool in the middle of the courtyard and with the small channels around, filled with beautiful lotus. 
With this idyllic atmosphere, the hotel is like an oasis in the middle of Thailand for all travelers.
The ruins of the old capital city (more than 700 years old) brings an imagination of the brilliance and beauty the city had been centuries ago.
The many channels around the city areas let assume a very efficient city planning. The temples with all these Buddha’s seem to be a bit different to Ayuthaya, are influenced by the former architecture of burma.
Hook, a very good colleague of my girlfriend, thaught me some tricks in photography. We made a lot of photos and I think, I could improve the quality of my shots.

Sukhothai has been very nice, but we still had about 4 hours driving with the car to Chiang Mai, the northern city. On the way there, we stopped in a very old temple, which is still in use. Behind the building with the ash of Buddah, a small hut drawed our attention. In the door of this hut where a small hole. If you go inside and close the door, a natural projection of the building with the ash of Buddah gets visible. It is really amazing an not fake! This phenomena is holy and no woman is allowed to enter this hut.
In Chiang Mai, we went for dinner in a restaurant serving the local food of the northern thai. A dance performance showed the different dance styles of Thailand.

The ruins of Sukhothai

The ruins of Sukhothai

The next day, we head off to Mae Cheam, a small village in the middle of the mountains, still belonging to the district of Chiang Mai. On the way there, we took bath in a hot spring. A lot of people are visiting this place and boiling some eggs. Seems to bring luck and good health to eat eggs boiled in this hot spring.
Mae Cheam has only 4 hotels and 3 of them where fully booked…
We rent a bungalow on the last one, it was the emergency bungalow of the owner, very dirty and in a bad condition. After complaining, we go the room of some people, which did not come yet. But we had to wait until they cancel their booking. Afterwards we went to a very nice hotel with only four rooms (which we wanted to go first) and booked the rooms for the next day. 
The night in the first hotel was a bit cold and we did not have a lot of space, but at least we had a ‘almost’ clean place to sleep. In morning, we searched a temple, where my girlfriend can make her merit. First we found a temple with a holy spring, where Buddah drank from, but unfortunately all monks where out, so we had to search further. Finally we found a small, old temple where we made a merit to an old monk. While hook and me shot some photos, my girlfriend talk to the monk about the religion culture in the mountain. 
The afternoon and night, we spent  with drinking coffee and relaxing in the fabulous  bungalow hotel we booked the day before. The house was made out of teak wood and the small bungalows with the platforms in between integrated into the garden is very beautiful. Rice fields surround the hotel and far away the forested peaks of the mountains were in sight.

Mae Cheam

Mae Cheam

 

 

The way back to Chiang Mai, we visited the Orb Laung national park, where the Mae Cham river is flowing in the canyon. Special is the view over the whole valley on the view point on top of the hill and the prehistoric paintings. The night in Chiang Mai and the seven hours back to Bangkok were not  really spectacular. 

The after a few days in Bangkok we took the bus to Kuhra Buri (12 hours) near Phuket. With the speed boat we reached the national park Mu Kho Surin. Surin is a small island, with white beaches and cyan, glass clear water.
There is a small restaurant and you can rent a tent. My girlfriend went there since many years and knows the stuff quite well, so we got the best tent and sometimes some special menus.
Surin is one of the best spots in Thailand for snorkeling. The reef with all its beauty provides a lot of animals to see. Among other thing you can see turtles, moraines, sharks, stingrays  and a lot of colorful fishes. Unfortunately, it was very windy and the waves were quite high, so we couldn’t go for snorkeling a lot, but we enjoyed the see with the sunshine and relaxing.
The way back to the mainland was quite adventures, the see was very wavy, some passengers had to fight with the see sick and nothing remained dry. 

Mu Kho Surin

Mu Kho Surin

 

 

Back in Bangkok we used the remaining time for shopping :) On the 17th january we head back home.

Have a look at the pictures:
Sukhothai
Chiang Mai
Mae Cheam
Mu Koh Surin

Tags: , ,

How to check whether a class implements an interface

Monday, December 15th, 2008 | Programming | No Comments

If we work with objects, it is not difficult to determine if a class implements an interface. This can be done with the is keyword.
But it gets difficult if we work with reflection. The type object of a class, contains a method called IsSubclassOf, but if we try to use it with an interface it returns false in any case and if we try to get all implemented interfaces and search the one we need, we’ll have to much work with this simple issue.

So how can we do this in a very easy way? I found the answer here. To shorten this long description, I’ll give you the answer right here:

typeof(IFoo).IsAssignableFrom(bar.GetType());
typeof(IFoo).IsAssignableFrom(typeof(BarClass));

The method IsAssignableFrom checks whether the type can be assigned from another. It takes a type objects as an argument an returns true if the type can be assigned.

Tags: ,

Debbuging trick for Xcode

Wednesday, November 19th, 2008 | Programming | 3 Comments

If you make an error which throws an exception, its sometimes quite hard to trance the error. Usually you have to set a breakpoint and step thru the code to find the line which throws the exception.

Woudn’t it be better, if the debugger stops automatically at the line of code, which throws the exception? I say yes, such things can make life easier and it is possible, since Xcode provides a feature called symbolic breakpoints.
To achieve this behaviour go to Build/Manage breakpoints/Add symbolic breakpoint and enter objc_exception_throw
Now create a programmatical error in your code (e.g. try to get an object in a NSArray with a non existing index) and start the debugger (Apple + Y). The debugger will stop exactly on the line of code, where the exception has been thrown.

Tags: , , ,

Check nullable types

Friday, November 7th, 2008 | Programming | No Comments

C# provides a feature for object-relationship mapping. Since a date time field on the database can be empty but the DateTime type in C# can not be set to null, there is a solution called nullable types.

The syntax for is:

DateTime? date;

The problem is, the type of this object is not DateTime, so how it’s possible to check a nullable type? 
It’s quite easy since all nullable types are of the type Nullable<>.  To compare the previous variable date you can use following code:

date.GetType() == typeof(Nullable)

Tags: ,

IPhone SDK on G5 PPC

Friday, October 17th, 2008 | iPhone | 64 Comments

<!–adsense#Google Adsense-Banner–>Officially the iPhone SDK requires an Intel Mac with OSX 10.5. Since I have a four year old dual G5, which is still running like a young dear, I don’t want to buy a new Mac just for writing iPhone Applications.

After some research, I found out, that it’s possible to make it work on PPC since the iPhone SDK are universal binaries.

To share my knowledge, I write a small tutorial. Note, that I don’t take responsibility, for any defects cause somebody used my code!

How to get the iPhone SDK to work on PPC Macs

Most of the tutorials I found in the Web are not up to date, because there where no “Aspen” packages anymore. With the iPhone SDK for IPhone OS 2.1 (build 9M2517) you can follow these steps:
1. Download the official iPhone SDK here.

2. Mount the .dmg image and install the iPhone SDK (the iPhone SDK will be grayed out!).

3. After rebooting the Mac, mount the image again and go to the folder Package. Install all packages which have iphone in the name (e.g. Simulator, SDK, Documentation).

4. Go to the folder /Platforms on the local HD and copy the iPhone.platform and the iPhoneSimulator.platform folders to /Developer/Platform.
Don’t copy the whole platforms folder, Xcode will not run correctly anymore!

5. Now we come to the interesting part. Xcode has now access to the iPhone SDK, you can already create iPhone projects, but Xcode still wants to compile the sources for the Intel architecture. To change that, open the folder /Developer/Platforms/iPhoneSimulator.platform/Developer/
Library/Xcode/Specifications/
.
In this folder you will find the file iPhone Simulator Architectures.xcspec. Make a backup and open it in any text editor. The content should look something like this:

(
// 32-Bit
{ Type = Architecture;
Identifier = Standard;
Name = "Standard (iPhone Simulator: i386)";
Description = "32-bit iPhone Simulator architectures";
ListInEnum = YES;
SortNumber = 1;
RealArchitectures = ( i386);
ArchitectureSetting = "ARCHS_STANDARD_32_BIT";
},

// Old-style Debug
{ Type = Architecture;
Identifier = Native;
Name = "Native Architecture of Build Machine";
Description = "32-bit for build machine";
ListInEnum = YES;
SortNumber = 101;
ArchitectureSetting = "NATIVE_ARCH";
},

// Intel
{ Type = Architecture;
Identifier = i386;
Name = "Intel";
Description = "32-bit Intel";
PerArchBuildSettingName = "Intel";
ByteOrder = little;
ListInEnum = NO;
SortNumber = 105;
},
)

6. Change the line “RealArchitectures = ( i386);” to “RealArchitectures = ( i386, ppc);“.

7. Add the architecture configuration for G3, G4 an G5, the edited file should now look like this.

(
// 32-Bit
{ Type = Architecture;
Identifier = Standard;
Name = "Standard (iPhone Simulator: i386, ppc)";
Description = "32-bit iPhone Simulator architectures";
ListInEnum = YES;
SortNumber = 1;
RealArchitectures = ( i386, ppc7400 );
ArchitectureSetting = "ARCHS_STANDARD_32_BIT";
},

// Old-style Debug
{ Type = Architecture;
Identifier = Native;
Name = "Native Architecture of Build Machine";
Description = "32-bit for build machine";
ListInEnum = YES;
SortNumber = 101;
ArchitectureSetting = "NATIVE_ARCH";
},

// G3
{ Type = Architecture;
Identifier = ppc;
Name = "Minimal (32-bit PowerPC only)";
Description = "32-bit PowerPC ";
PerArchBuildSettingName = "PowerPC";
ByteOrder = big;
ListInEnum = No;
SortNumber = 201;
},

// G4
{ Type = Architecture;
Identifier = ppc7400;
Name = "PowerPC G4";
Description = "32-bit PowerPC for G4 processor";
ByteOrder = big;
ListInEnum = NO;
SortNumber = 202;
},

// G5 32-bit
{ Type = Architecture;
Identifier = ppc970;
Name = "PowerPC G5 32-bit";
Description = "32-bit PowerPC for G5 processor";
ByteOrder = big;
ListInEnum = NO;
SortNumber = 203;
},

// Intel
{ Type = Architecture;
Identifier = i386;
Name = "Intel";
Description = "32-bit Intel";
PerArchBuildSettingName = "Intel";
ByteOrder = little;
ListInEnum = NO;
SortNumber = 105;
},
)

Now you should be able to compile the iPhone project and run the app in the iPhoneSimulator. I never tried to put an App into the AppStore, but I think it should work.

Please let me know if my post could help you, or if you have any questions!

Further links to this issue:
http://linuxclub.blogspot.com/2008/07/iphone-sdk-installtion-on-powerpc-g4.html
- http://forums.ilounge.com/showthread.php?t=223546
- http://www.iphoneatlas.com/2008/03/10/surprise-iphone-sdk-also-works-on-powerpc-macs/

Tags: , , ,