Saturday, January 23, 2010

Objective-C to C#

This is my personal reference to help me learn Objective-C. The example Ojective-C code is taken from Scott Stevenson's Learn Objective-C. It's a great tutorial. Use this reference to help understand the difference (likeness) between Objective-C and C#.

Objective-C

C#

Message Method

Calling Methods

[object method]; object.Method();
[object methodWithInput:input]; object.MethodWithInput(input);
output = [object methodWithOutput];output = object.Method();
id myObject = [NSString string];object myObject = new StringBuilder();
NSString* myString = [NSString string];StringBuilder myString = new StringBuilder();
It's really: string myString;

Nested Messages

 
[NSString stringWithFormat:[prefs format]]; NSString.StringWithFormat(prefs.format());

Multi-Input Methods

-(BOOL)writeToFile:(NSString*)path atomically:(BOOL)useAuxiliaryFile; /// <param name="useAuxiliaryFile">atomically</param>
bool WriteToFile(string path, bool useAuxiliaryFile);
BOOL result = [myData writeToFile:@"/tmp/log.txt" atomically:NO];bool result = myData.WriteToFile(@"/tmp/log.txt", false);

Accessors

photo.caption = @"Day at the Beach";
output = photo.caption;
photo.Caption = "Day at the Beach";
output = photo.Caption;

Creating Objects

NSString* myString = [NSString string];StringBuilder myString = new StringBuilder();
NSString* myString = [[NSString alloc] init];StringBuilder myString = new StringBuilder();
NSNumber* value = [[NSNumber alloc] initWithFloat:1.0];float value = 1.0;

Designing a Class Interface

Photo.hPhoto.cs
#import <Cocoa/Cocoa.h>

@interface Photo : NSObject {
    NSString* caption;
    NSString* photographer;
}

@property (retain) NSString* caption;
@property (retain) NSString* photographer;

@end
interface IPhoto : INSObject
{
    string Caption { get; set; }
    string Photographer { get; set; }
}

Class Implementation

#import "Photo.h"

@implementation Photo

@synthesize caption;
@synthesize photographer;

- (void) dealloc
{
    self.caption = nil;
    self.photographer = nil;
    [super dealloc];
}
 
@end
class Photo : IPhoto
{
    public string Caption { get; set; }
    public string Photographer { get; set; }
}

No comments:

Post a Comment