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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>