ios

iOS for C# Developer – part 2: strings

This post is part of the series: iOS for C# Developer. First part can be found here.

String operations in Objective-C are very verbose in comparison to C#.

Let’s assume the following string definition for all below examples:

NSString *str = @"Some string. Another string.";

Concatenation

I think this is the most common operation. In C# it is very simple:

string result += " Appended string.";

* For concatenation in C#, consider using StringBuilder class (if performance matters).

In Objective-C, NSMutableString type has to be used. Thus, if we have NSString created, we have to do the following:

NSMutableString *temp = [[NSMutableString alloc] initWithString:str];
[temp stringByAppendingString:@" Appended string."];
str = temp;

A bit of work, huh?

Substring

To get substring from letter 3 to 7 in C#:

string result = str.Substring(3,5);

In Objective-C:

NSString *result = [str substringWithRange:NSMakeRange(3,5)];

Pretty straightforward.

Split

To split sentences in our sample string in C#, we would do:

string[] result = str.Split(". ");

In Objective-C:

NSArray *result = [str componentsSeparatedByString:@". "];

Also, pretty similar.

Replace

This operation is much more verbose than its equivalent in C#. To replace spaces with underscores, in C# we do:

string result = str.Replace(" ", "_");

In Objective-C:

NSString *result = [str stringByReplacingOccurrencesOfString:@" " withString:@"_"];

Looks pretty the same, but long, custom names preceding actual parameters make code unnecessary long (IMO).

Real-world example

Usually we need a few string operations working together. Let’s apply above operations together. For example: we want to get only the second sentence from our string with underscores instead of spaces.

In C#:

string result = str.Split(new [] {". "}, StringSplitOptions.RemoveEmptyEntries)[1].Replace(' ','_');

In Objective-C:

NSString *result = [[str componentsSeparatedByString:@". "][1] stringByReplacingOccurrencesOfString:@" " withString:@"_"];

Summary

Some of above operations are easier in Swift (e.g., concatenation looks the same like in C#), but some are still very verbose (e.g., substring, replace). However, the syntax is more similar to C#. The message passing syntax is something you need to get use to in Objective-C, not only in case of string operations.


iOS for C# Developer – part 1: Classes and creating objects

In this series I would like to present an overview of differences and similarities in developing iOS and C# apps.

First part is about Object-Oriented features. If you are C# developer and you are starting with Objective-C, Object-Oriented terminology might be confusing.

Interface

In Objective-C, interface is a class declaration (not existing in C#). It is like header file in C++. It has even the same extension: .h. This is sample interface:

@interface Example

+ (void)someStaticMethod;

- (NSInteger)someInstanceMethod:(BOOL)param1 calledWith:(NSInteger)num;

@end

Static (class) methods are distinguished by + sign. Instance method starts with - sign. Return types are in brackets. Parameters (brackets and name) are preceded by custom name. In class implementation only parameter name matters.

Implementation

In addition to interface (equivalent of class declaration), Objective-C classes have also implementation files with .m extension (equivalent of .cpp files in C++). Example implementation for previous interface (class declaration) can look like that:

@implementation Example

+ (void)someStaticMethod
{
  // implementation
}

- (NSInteger)someInstanceMethod:(BOOL)param1 calledWith:(NSInteger)num
{
  if(param1) {
    return num*2;
  } else {
    return num;
  }
}

@end

Protocols

Protocol is equivalent of interface in C#. This is sample protocol definition:

@protocol SampleProtocol
- (void)protocolMethod1;
- (void)protocolMethod2;
@end

To take advantage of this protocol in some class, it has to be stated in angled brackets, in the interface definition:

@interface Example : NSObject <SampleProtocol>
+ (void)someStaticMethod;
- (NSInteger)someInstanceMethod:(BOOL)param1 calledWith:(NSInteger)num;
@end

Then, its methods have to be implemented in the implementation file:

@implementation Example 

+ (void)someStaticMethod 
{ 
  // implementation 
} 

- (NSInteger)someInstanceMethod:(BOOL)param1 calledWith:(NSInteger)num 
{ 
  if(param1) { 
    return num*2; 
  } else { 
    return num; 
  } 
} 

- (void)protocolMethod1 
{ 
  // implementation 
} 

- (void)protocolMethod2 
{ 
  // implementation 
} 

@end

There are two types of methods in protocol:

  • required (default)
  • optional

In previous protocol, both methods are required, because it is a default mode. This means, both has to be implemented in the class that use the protocol. In order to make second method optional, keyword @optional has to be used:

@protocol SampleProtocol

- (void)protocolMethod1;

@optional
- (void)protocolMethod2;

@end

All methods declared after @optional keyword are optional. In order to declare required method after that, @required keyword has to be used:

@protocol SampleProtocol

- (void)protocolMethod1;  // required method

@optional
- (void)protocolMethod2;  // optional method
- (void)protocolMethod3;  // optional method

@required
- (void)protocolMethod4;  // required method

@end

Instantiating objects

Creating instance of object has two steps: allocation and initialization. To create instance of Example class defined above, message passing syntax is used:

Example *obj = [[Example alloc] init];

Shortcut for above object creation:

Example *obj = [Example new];

When the class has a constructor with parameters, e.g.:

@interface Example : NSObject {
  NSInteger *sampleProperty;
}
- (id) initWithParam:param;
@end

@implementation Example

- (id) initWithParam:(NSInteger)param
{
  self = [super init];
  if (self) {
    self.sampleProperty = param;
  }
  return self;
}

@end

Initialization looks as follows:

Example *obj = [Example initWithParam:25];

Summary

  • Interface – class declaration
  • Implementation – class body (implementation of declared methods in class interface)
  • Protocol – the same construct as interface in C#
  • Object creation: Example *obj = [[Example alloc] init];

Getting started with iOS Development

iPhones

I started iOS development last year. Here, I would like to summarize all (good and worth to spend time on) resources I have been using since that time.

Tools

Unfortunately, or fortunately, there is only one right set of tools: MacBook and xCode. Of course you can use terminal and Vim but…

Objective-C

First step in learning iOS Development is to learn Objective-C. Good place to start is free Try Objective-C on CodeSchool. There is also Programming with Objective-C on Mac Developer Library, but it is more in documentation style, than tutorial. Choose whatever you like better. To get more deeply there is a great book written by Stephen G. Kochan: Programming in Objective-C. It is for beginners, but discuss all aspects of the language in details.

Programming in Objective-C

iPhone/iPad programming

To get started, there are two nice tutorials:

After getting familiar with the platform, it is time to become more advanced. My favorite, and the best in my opinion is Stanford course: Developing iOS 7 Apps for iPhone and iPad by Paul Hegarty. He is a great teacher. I really recommend you to go through all lectures and do all homeworks if you think seriously about becoming iOS developer.

Developing iOS 7 Apps for iPhone and iPad

To summarize and sort out your knowledge, there is another great book: iOS Programming: The Big Nerd Ranch Guide.

iOS Programming: The Big Nerd Ranch Guide

 

UPDATE: Swift

At the WWDC 2014 conference, Apple announced new programming language: Swift. This is something, that everybody was waiting for. Finally, we have higher level of abstraction in top of Objective-C, whose expressiveness was simply uncomfortable and not developer-friendly. Swift uses the Objective-C runtime, allowing Objective-C and Swift code to run within a single program. Swift is pretty new thing, but there is already a lot of online resources to learn it. Check Swift Cheat Sheet as high-level overview. More detailed starting point is Ray Wenderlich’s Swift Tutorial: part 1, part 2 and part 3. There is also nice To do list app video tutorial. For more, check Swift at Apple Developer website and free book The Swift Programming Language (bible, over 800 pages).

Summary

All of these resources will give you solid fundaments for iOS development. After getting familiar with them you will be ready to create your own apps and publish them on App Store. Of course it is not required to go through all of them before you start creating your apps. You can just go through basic tutorials and publish your app. However, it may save you a lot of time, which you will need to spend figuring out things. Additionally, you will learn how to do things in a right way.

UPDATE2: Recently, Udacity released beginner’s guide to Swift Playgrounds, and full blown Intro to iOS App Development with Swift.

UPDATE3: On iTunes, there is already available updated Developing iOS 8 Apps with Swift from Stanford by Paul Hegarty.


The future of Mobile Apps

I think that in next 5 years Web Mobile apps will be more popular than classic Mobile apps we are using today.

Me, June 28, 2013

That is what happend in case of PCs. 10 years ago we were installing apps instead of just use them in the browser. Now we can edit Word documents, play games and even use IDE in Web Browser. I am not saying that it will be no classic Mobile apps at all, but e.g. apps like Calendar, gmail, Evernote, OneNote or games should be easilly accessible through Mobile Web Browser. The advantage of that would be lack of necessity to install bunch of apps.

What that means for developers? People who are currently working as Mobile Developers will need to learn Web Development. People who are currently working as Web Developers will need to learn Mobile Development. Additionally, future developers will not necessary need to know all different platforms (iOS, Android, WP), because they will be able to create apps in HTML5 and JavaScript (which should be well supported and compatible with Mobile Web Browsers in next 5 years).

This is my prediction. We’ll see what happens after 5 years.