About the Author

Software Engineer @ Interknowlogy

Comparing similarities/differences between C# and Objective-C

It’s been a little over a month and I’ve been grinding through learning iOS development using Xcode and Objective-C. I come from a .NET background using Visual Studio and C# and find it slowly becoming easier to understand the Objective-C syntax. I’ve been primarily using the Nerd Ranch Book to learn iOS development but recently bought a great book called Migrating to iPhone and iPad for .NET developers, http://www.amazon.com/Migrating-iPhone-iPad-NET-Developers/dp/1430238585. Today I have been skimming through a few chapters and jumped into Chapter 4, Going Deeper: .NET, Objective-C and the iOS SDK. The earlier chapters mentioned setting up your development environment, overview of iOS SDK and understanding third-party tools which I already reviewed. Anyhow, below are notes I’ve quickly taken from Chapter 4 that discusses the similarities and differences in Objective-C and C# involving Class declaration, method declaration, Properties, Strings and Interfaces/Protocols. This is a good way to see how to start migrating in writing Objective-C code from a .NET background. Stay tune to see more notes on the differences/similarities to help understand Objective-C syntax more.

Class Declaration

Both .NET and Objective-C are object-oriented languages, and so the definition of a

class is a key construct for the language. Consider the following Objective-C and .NET

C# examples, shown together.

.NET C#

<span style="font-family: TheSansMonoCondensed-Plain;">Class AClass : Object</span>

{

int aValue;

void doNothing();

String returnString();

}

Objective-C

@interface AClass : NSObject

{

int aValue;

}

– (void)doNothing();

+ (NSString)returnString();

@end

Both of these code segments declare a new class object that inherits from an object class. It has a default integer member variable called aValue, and two methods. One method is called doNothing() and returns nothing and takes no parameters. The other method is returnString(), which returns a string but also takes no parameters.

You may also notice that different characters precede the method declarations.

Method Declaration

An obvious companion to the class is the methods that provide the necessary functionality for the class. Methods may be defined as instance methods or class methods, as indicated by the character that precedes their declaration, as follows:

* A class method is indicated by a plus (+) character. It is the same as a C# static method. Only a single implementation exists, and it is associated with the class type.

*An instance method is indicated by a minus (-) character. Here, the method is associated with an instance object associated with the class.

The following are .NET C# and Objective-C examples.

.NET C#

public static void aClassMethod();

public void anInstanceMethod();

Objective-C

+ (void) aClassMethod;

– (void) anInstanceMethod;

Now let’s look at how to pass parameters to the method. Consider the following examples.

.NET C#

String addStrings( String a, String b);

Objective-C

– (NSString) addStrings (NSString *) a secondParm2:(NSString *) b;

This syntax creates a method called addStrings, which concatenates strings given as two parameters and returns a string value. The way you invoke the method is important, too since the parameters are order-sensitive.

[ addStrings s1, secondParm:s2 ];

Properties

The use of properties has long been the mainstay for accessing class objects, and in doing so, managing how they are accessed and what they return. Such class members are known as instance variables, as the property manages access to the actual value associated when an instance of the class is created. They can also be used to control scope and to hide any complexities associated with returning the property value.

Objective-C can also help by synthesizing (automatically creating behind the scenes) the accessor methods (the getter and setter) and creating the instance variable required. It also ensures that the memory management surrounding instance variables is handled appropriately. Consider the following examples.

.NET C#

// Definition of your instance variable either within the class, or as a minimum, in the scope of the class

string _name;

// Definition of your property accessor methods are within the class

public string name

{
get { return _name; }
set { _name = value; }
}

Objective-C

// Definition of your property within your class header file (.h)

@property (nonatomic, retain) NSString *name;

// Synthesis of your property in the implementation file (.m)

@synthesize name = _name;

You’ll notice in the C# example that C# has no equivalent to the synthesis model for accessing an instance variable. You must write accessor methods manually. This is reminiscent of the Objective-C found in Xcode 3. x, which is still valid for Xcode 4 but not the best practice. I recommend writing accessor methods in Xcode 4 only when necessary, usually in cases where more complex processing is required when returning property values.

Strings

Because Objective-C is based on the C programming language, you are free to use and manipulate strings in the C way, through the use of pointers and strings essentially being character arrays. There is no C# comparison, as C# doesn’t support pointers, so we’ll use strings, string constants, and more advanced features, such as string localization as comparisons.

Consider the following examples for representing a string constant, which is a static string value that cannot be changed.

.NET C#

// Define a constant string using the following syntax.

const string example=”This is a constant string”

// Using this syntax to set a string attribute

window.title = example;

Objective-C

// Define a constant string using the following syntax.

// @”This is a constant string”

// Using this syntax to set a string attribute

window.title = @”Main Window Title”;

The following examples show the definition of a string using the respective string class provided within the language. Note that using the class with the @ symbol creates an immutable string—that is, a string that cannot be changed.

.NET C#

String string1 = @”This is an immutable string”;

// Both of these statements are the same

String string2 = “This is a mutable string”;

String string3 = new string(“This is a mutable string”);

Objective-C

NSString *string1 = @”This is an immutable string”;

NSString *string2 = “This is a mutable string”;

Interfaces and Protocols

An Objective-C interface is actually a C# class, and an Objective-C protocol is actually a C# interface—confusing, eh?

We’ll start with C# and the definition of a class, with member variables and methods. C# uses the class keyword and syntax to define a class; Objective-C uses the @interface compiler directive.

If we focus on what C# calls an interface, which Objective-C refers to as a protocol, this uses a different syntax. In Objective-C, a protocol declares methods that can be implemented by any class, or indeed, be used as a variable. Consider the following example. It defines an interface, which is then implemented by a class. You use angled brackets within the interface declaration to declare your class implements the named type for implementation or specialization.

.NET C#

// Definition of your interface template

interface IEquatable<T>

{

bool Equals(T obj);

}

// Implementation of your class

// which realizes the interface

// defined above

public class MyClass : IEquatable<MyClass>

{

// Implementation of IEquatable<T> interface

public bool Equals(MyClass c)

{

// implementation here

}

}

Objective-C

// Definition of your interface template

@protocol IEquatable

– (bool) Equals : (NSObject*) a ;

@end

@interface MyClass : NSObject <IEquatable>

{

// Some methods here

}

@end

// Implementation of your class

// which realizes the interface

// defined above

@implementation MyClass

// Implementation of IEquatable<T> interface

– (bool) Equals : (NSObject*) a

{

// implementation here

}

@end

A class definition can declare an implementation of more than one interface simply by separating the interfaces by a comma, like so:

Public class MyClass : NSObject <IEquatable, AnotherProtocol>

As you can see, it’s quite similar. One key difference is where Objective-C uses protocols as variables or as an argument to a method, which is often the case when an interface’s implementation is used as a callback function.

Understanding ViewControllers

Chapter 7 – View Controllers
To be honest, I quickly jumpted to Chapter 10, since that is the chapter to start working on the Homepwners application.  While only skimming through the previous chapters, I should of spent more time reading Chapter 7 on View Controllers.  So before I continue working on the next chapter on the Homepwners application, I would like to write a blog post on View Controllers.

Most iOS applications will need multiple “screens”.  In iOS development, each screen typically gets its own controller and XIB file.  Each controller has a view that gets placed on the winow.  Thus, we call these controllers, view controllers.  A view controller is a subclass of UIViewController and has an instance variable called, view.  And, we typically need an object to take care of the view swapping for us.  For this chapter, the example application will show the swapping is done by a UITabBarController. 

The iOS example application for this chapter contains two view controllers.  One displays the HypnosisView and the other will let the user get the current time by tapping a button.  The swapping of views uses the UITabBarController.

Now when creating views for the view controllers, there are two ways to do this: create the view programmatically or create a XIB file.  A good rule-of-thumb in deciding when to do one versus the other is if the view has no subviews, create it programmatically.  For Chapter 11 when we added a header control above the UITableView, we created a new viewcontroller and view.  If you remember, we created the view by creating a new XIB file made up of a UIView and 2 UIButtons, Edit and New.  We then made a action connection from each UIButton to the viewcontroller.  We then made a outlet connection from the FileOwner to the UIView control.  Then we load the XIB file manually using NSBundle in the viewcontroller by implementing headerView.  Reminder, XIB files are typically used to create the window and application delegate and to create the view for a view controller.

Chapter 7 helped me understand viewcontrollers much more in depth.  Stay tune for more implementation on the Homepwner class.

Retrospective on learning iOS development so far

Before I continue on to the 4th blog post on my series of creating a Homepwner iPhone app using the Big Near Ranch book, I just wanted to give my opinion so far on learning iOS development. I would have to say learning Xcode and objective-c from a .NET background has been been difficult at times, but overall a fun learning experience. Obviously the objective-c syntax takes time to getting used to and learning the IDE of Xcode is different than Visual Studio’s IDE. The way you bind UI controls in Xcode using actions and outlets is very different than how you would bind in WPF. I know as I grind through and continue learning iOS programming, a lot of things will become second nature. Look forward to the next blog post on Camera for the Homepwner application in the next few days.

Also, I have the source code for the first blog post, UITableView and UITableVIewController. I will post a link to download the source code later today. In the next few days, I will also make available the source code for the second and third blog posts. I’m in the middle of blog post 4, so stay tune for that. Probably over the weekend, depending on my schedule. Also, thanks for following this blog series, as its helped me a lot to organize my thoughts and continue learning iOS development. Thanks!

iOS development Part 3 UINavigationController

Part 1: UITableView and UITableVIewController

Part 2: Editing UITableView (current)

Part 3: UINavigationController

Part 4: Camera

Part 5: UIPopoverController and Modal View Controllers

Part 6: Saving, Loading and Multitasking

Part 7: Subclassing UITableViewCell

Part 8: Core Data

Part 9: Localization

For Chapter 12, we will extend the Homepwner application and use the UINavigationController to add a drill-down interface to allow the user to view and edit the details of a selected Possesion item. Currently, you can only display the list of Possession items, move items, delete and add a new Possession to the ItemsviewController. Now we will wire up the Edit toggle button in the UINavigationBar.

After adding the UINavigationController, we will make the ItemsViewController that displays all the Possession items, the UINavigationController’s rootViewController. Then, we’ll create another subclass of UIViewController that can be pushed onto the UINavigationController’s stack. Thus, when a user selects one of the possession rows, the new UIViewController’s view will slide onto the screen. This new view controller will allow the user to view and edit the properties of the selected Possession.

At the end of this chapter, we will have a navigation controller, a navigation bar and two view controllers. The user will be able to tap a row in ItemsViewcontroller’s table view and have the new ItemDetailViewcontroller’s view slide onto the screen and display the properties of the selected Possession instance.

iOS development Part 2 – Editing UITableView

In the last blog post and last chapter (Chapter 10) of the Big Nerd Ranch iOS book, I created an application that displays a list of Possession items in a UITableView control.  I will add the source code and any gotchas I went through in that blog post in a little bit.  For this blog post, we will learn how to edit the content (Possession items) in a UITableView.  The UITableView has an editing property which allows you to move, delete and insert rows.  However, editing mode does not allow the user to edit the content of a row, the description property of the Possession item.

When in editing mode, a header view will appear about the UITableView that consists of 2 buttons, Edit and Add buttons.  Tapping the Edit button will toggle the editing mode of the UITableView.  Tapping the Add button will allow you to add a new Possession item to the UITableView.  Along with the 2 buttons in the HeaderView, there will be a delete button to the left of each row in the UITableView.  After this chapter, that will be all for the UITableView control and on to the UINavigationController control.  Stay tuned for an update with source code and gotchas I went through in implementing the edit functionality for the UITableView.

Part 1: UITableView and UITableVIewController

Part 2: Editing UITableView (current)

Part 3: UINavigationController

Part 4: Camera

Part 5: UIPopoverController and Modal View Controllers

Part 6: Saving, Loading and Multitasking

Part 7: Subclassing UITableViewCell

Part 8: Core Data

Part 9: Localization

iOS development Part 1 – UITableView and UITableViewController





I’ve been learning off and on iOS development by reading two main books, Xcode 4 iOS Development Beginner’s Guide (http://www.amazon.com/Xcode-iOS-Development-Beginners-Guide/dp/1849691304) and iOS Programming The Big Nerd Ranch Guide (http://www.amazon.com/iOS-Programming-Ranch-Guides-ebook/dp/B004Z2NQJQ).  I plan to start a series of blog posts to document what I’ve learned and for others to gain insight as well.  So far in reading a little from both books, they each have very simple sample projects to get your feet wet in learning how Xcode IDE is used, writing objective-c code and MVC design pattern.  Today, I’m going to focus on a more complex and realistic sample application that in the Big Nerd Ranch book.

The sample application starts off in Chapter 10, UITableView and UITableViewController, called Homepwner that basically keeps an inventory of all your possessions.  In the case of a fire or other catastrophe, you’ll have a record for your insurance company.  The Homeowner application will grow over the course of 9 chapters in the book.  The first chapter, Chapter 10, will present a list of Possession objects in a UITableView.  So keep coming back to this blog to follow the progression or leave comments if you have a copy of the Big Nerd Ranch and want to develop along with me through the 9 chapters. 

Part 1: UITableView and UITableVIewController (current)

Part 2: Editing UITableView

Part 3: UINavigationController

Part 4: Camera

Part 5: UIPopoverController and Modal View Controllers

Part 6: Saving, Loading and Multitasking

Part 7: Subclassing UITableViewCell

Part 8: Core Data

Part 9: Localization