Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Objective-C for Rubyists

Objective-C for Rubyists

Objective-C might look like a crazy, complex and verbose language to the seasoned Rubyist. In reality, they share many features. This allows you to use your knowledge of Ruby to quickly get started with Objective-C. In this talk, I give an overview of the syntax and semantics of Objective-C and compare and contrast it with Ruby where appropriate.

Bf725cb6d25d664d07023f57cb985bc5?s=128

Mikael Konutgan

March 01, 2014
Tweet

Transcript

  1. Objective-C for Rubyists

  2. Mikael Konutgan iOS Developer, aaa – all about apps GmbH

    !2
  3. Why Objective-C?

  4. !4

  5. !5

  6. A Quick Example

  7. Ruby numbers = [42, 14, 73] ! numbers.each_with_index do |number,

    idx| puts "#{idx} -> #{number}" end
  8. Objective-C NSNumber *a = [NSNumber numberWithInteger:42]; NSNumber *b = [NSNumber

    numberWithInteger:14]; NSNumber *c = [NSNumber numberWithInteger:73]; NSArray *numbers = [[NSArray alloc] initWithObjects:a, b, c, nil]; ! for (NSUInteger index = 0; index < [numbers count]; index++) { NSLog(@"%lu -> %@", index, [numbers objectAtIndex:index]); } ! [numbers release];
  9. Modern Objective-C NSArray *numbers = @[@42, @14, @73]; ! [numbers

    enumerateObjectsUsingBlock:^(NSNumber *number, NSUInteger idx, BOOL *stop) { NSLog(@"%lu -> %@", idx, number); }];
  10. Objective-C

  11. • A strict superset of C • Object oriented, but

    everything is NOT an object • A dynamic runtime • Static or dynamic typing for objects !11 Objective-C
  12. Modern Objective-C • Object literals for arrays, hashes, numbers! •

    Automatic memory management!! • Enumeration with blocks!!! • Domain specific languages!!!! !12
  13. A strict superset of C Everything that works in C,

    works in Objective-C • Control flow: if, while, for • Primitive types, int, long, char, void *, const char * • The C standard library • UNIX system calls !13
  14. int n = 5; const char *str = "hello, world\n";

    unsigned long len = strlen(str); ! if (len > 0) { int i = 0; while (i < n) { printf("%s", str); i++; } } C
  15. Booleans BOOL shouldBeginEditing = YES; ! BOOL shouldEndEditing = NO;

    !15
  16. Defining Classes !16

  17. # user.rb ! class User end !17 Ruby

  18. // KMUser.h ! @interface KMUser : NSObject ! @end !18

    Objective-C
  19. // KMUser.m ! @implementation KMUser ! @end !19 Objective-C

  20. class User attr_accessor :name, :last_name end !20 Ruby

  21. // KMUser.h ! @interface KMUser : NSObject ! @property (copy,

    nonatomic) NSString *name; @property (copy, nonatomic) NSString *lastName; ! @end !21 Objective-C
  22. // KMUser.m ! @implementation KMUser ! @end !22 Objective-C

  23. // KMUser.m ! @implementation KMUser ! @synthesize name = _name;

    @synthesize lastName = _lastName; ! @end !23 Objective-C
  24. Ruby class User attr_accessor :name, :last_name ! def initialize(name, last_name)

    @name = name @last_name = last_name end end
  25. // KMUser.h ! @interface KMUser : NSObject ! @property (copy,

    nonatomic) NSString *name; @property (copy, nonatomic) NSString *lastName; ! - (KMUser *)initWithName:(NSString *)name lastName:(NSString *)lastName; ! @end !25 Objective-C
  26. // KMUser.m ! @implementation KMUser ! - (id)initWithName:(NSString *)name lastName:(NSString

    *)lastName { self = [super init]; if (self) { _name = name; _lastName = lastName; } return self; } ! @end !26 Objective-C
  27. The Muffin Man @interface TheMuffinMan : NSObject ! - (BOOL)doYouKnowTheMuffenMan:(TheMuffinMan

    *)theMuffinMan; ! @end ! @implementation TheMuffinMan ! - (BOOL)doYouKnowTheMuffenMan:(TheMuffinMan *)theMuffinMan { return YES; } ! @end
  28. Using classes

  29. user = User.new("Mikael", "Konutgan") ! name = user.name last_name =

    user.last_name ! user.name = “Kristofer" user.last_name = nil !29 Ruby
  30. KMUser *user = [[KMUser alloc] initWithName:@“Mikael" lastName:@“Konutgan"]; ! NSString *name

    = user.name; NSString *lastName = user.lastName; ! user.name = @"Kristofer"; user.lastName = nil; ! name = [user name]; lastName = [user lastName]; ! [user setName:@“Kristofer"]; [user setName:nil]; !30 Objective-C
  31. Objective-C Messages

  32. • initWithName:lastName: ! • replaceObjectsInRange:withObjectsFromArray:range: !32 Selectors

  33. Selectors - (KMUser *)initWithName:(NSString *)name lastName:(NSString *)lastName;

  34. Ruby person.say_hello("Lukas")

  35. Objective-C [person sayHello:@"Lukas"];

  36. Dynamic message sending

  37. Ruby person.send(:say_hello, "Lukas", "French")

  38. Objective-C [person performSelector:@selector(sayHello:inLanguage:) withObject:@"Lukas" withObject:@"French"];

  39. SEL selector = NSSelectorFromString(@"sayHello:inLanguage:"); Objective-C !39

  40. Objects

  41. Objective-C • Objects are all pointers • But you (almost)

    never need to worry about that • Just don’t forget the star, when declaring variables or parameters
  42. Foundation • The “standard library” of Objective-C

  43. Ruby String

  44. Objective-C NSString

  45. Ruby Array

  46. Objective-C NSArray

  47. Ruby Hash

  48. Objective-C NSDictionary

  49. Objective-C NSMutableString NSMutableArray NSMutableDictionary

  50. Ruby names = ['Mikael', 'Kristofer', 'Lukas'] ! name = names[1]

  51. Objective-C NSArray *names = @[@"Mikael", @"Kristofer", @“Lukas”]; ! NSString *name

    = names[1];
  52. Ruby locations = { 'Mikael' => 'Vienna', 'Kristofer' => 'Istanbul',

    'Lukas' => 'Istanbul' } ! location = locations['Kristofer']
  53. Objective-C NSDictionary *locations = @{ @"Mikael": @"Vienna", @"Kristofer": @"Istanbul", @"Lukas":

    @"Istanbul" }; ! NSString *location = locations[@"Kristofer"];
  54. Why NS, KM, etc.?

  55. • Objective-C doesn’t have proper namespaces • We use 2

    or 3 letters to prefix all class names to prevent clashes • For example, the Foundation framework that defines strings, arrays, hashes etc. uses “NS” • “NS” stands for “NeXTSTEP” Prefixing classes
  56. Duck typing and introspection

  57. Duck typing When I see a bird that walks like

    a duck and swims like a duck and quacks like a duck, I call that bird a duck.
  58. Ruby sender.respond_to?(:to_f)

  59. Objective-C [sender respondsToSelector:@selector(floatValue)];

  60. Ruby def action(sender) if sender.class == Array # ... elsif

    sender.class == Hash # ... end end
  61. Objective-C - (void)action:(id)sender { if ([sender isKindOfClass:[UIButton class]]) { //

    ... } else if ([sender isKindOfClass:[UITapGestureRecognizer class]]) { // .. } }
  62. Blocks

  63. Block • Enumeration • Passing code around • Async tasks,

    completion handlers • Blocks are closures
  64. Ruby block = lambda { puts 'hello, world' } !

    block.call
  65. Objective-C void (^block)() = ^ { NSLog(@"hello, world"); }; !

    block();
  66. Grand Central Dispatch dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); ! dispatch_async(queue,

    ^ { // Long background task ! dispatch_async(dispatch_get_main_queue(), ^ { // Update the UI }); });
  67. How Do I Declare A Block in Objective-C? http://fuckingblocksyntax.com

  68. Domain Specific Languages

  69. Ruby (Bacon) describe 'A new array' do before do @ary

    = Array.new end it 'should be empty' do @ary.should.be.empty @ary.should.not.include 1 end end
  70. Objective-C (Kiwi) describe(@"Team", ^ { context(@"when newly created", ^ {

    it(@"should have a name", ^ { id team = [Team team]; [[[team name] should] equal:@"Black Hawks"]; }); it(@"should have 11 players", ^ { id team = [Team team]; [[[team should] have:11] players]; }); }); });
  71. The Objective-C Runtime

  72. The Objective-C Runtime #include <objc/runtime.h>

  73. The Objective-C Runtime • objc_msgSend • class_getMethodImplementation • objc_allocateClassPair •

    objc_getClassList • etc.
  74. Tools

  75. rubygems and bundler # Gemfile ! source 'https://rubygems.org' ruby '2.1.0'

    ! gem 'rack' gem 'vienna', '>= 0.4.0' gem 'thin'
  76. Cocoapods # Podfile ! platform :ios, '7.0' ! pod 'AFNetworking',

    '~> 2.0'
  77. Where to Go from Here

  78. Around the Web • iOS Developer Library • raywenderlich.com •

    Cocoapods
  79. Books • Objective-C Programming: The Big Nerd Ranch Guide •

    iOS Programming: The Big Nerd Ranch Guide • iOS 7 Programming Fundamentals • Programming iOS 7
  80. Thank You! • @mkonutgan on Twitter • @kmikael on GitHub

    • kmikael.com • me@kmikael.com