Tales@tdc

47
Objective-C Um pouco de arqueologia Tales Pinheiro @talesp, [email protected]

description

 

Transcript of Tales@tdc

Page 1: Tales@tdc

Objective-CUm pouco de arqueologia

Tales Pinheiro@talesp, [email protected]

Page 2: Tales@tdc

Mestre em computação pelo IME/USP

Head of Technologies na Newt Labs

Dev iOS na Shopcliq (http://shopcliq.com.br)

Incentivador da @selfsp NSCoder Night

http://meetup.com/NSCoder-Night-self-SP/

[self SP]; //http://groups.google.com/forum/#!forum/selfsp

Tales Pinheiro de Andrade

Page 3: Tales@tdc

Charles Babbage

Augusta Ada King

Page 4: Tales@tdc

Fortran

Analyticlal Engine Order Code

CPC Building Scheme

Boehm Unnamed Coding system

Sequentielle Formelübersetzung

Speedcoding

Laning and Zieler

IT

Algol

Simula

CPL BCPL B C

Smalltalk

40s - Primeiras linguagens

Page 5: Tales@tdc

Fortran

Analyticlal Engine Order Code

CPC Building Scheme

Boehm Unnamed Coding system

Sequentielle Formelübersetzung

Speedcoding

Laning and Zieler

IT

Algol

Simula

CPL BCPL B C

Smalltalk

Primeiras linguagens “Modernas”

Page 6: Tales@tdc

Fortran

Analyticlal Engine Order Code

CPC Building Scheme

Boehm Unnamed Coding system

Sequentielle Formelübersetzung

Speedcoding

Laning and Zieler

IT

Algol

Simula

CPL BCPL B C

Smalltalk

Paradigmas fundamentais

Page 7: Tales@tdc

Smalltalk

One day, in a typical PARC hallway bullsession, Ted Kaehler, Dan Ingalls, and I were standing around talking

about programming languages. The subject of power came up and the two of them wondered how large a language one

would have to make to get great power. With as much panache as I could muster, I asserted that you could define the “most powerful language in the world” in “a page of

code.” They said, “Put up or shut up.”

http://gagne.homedns.org/~tgagne/contrib/EarlyHistoryST.html

Page 8: Tales@tdc

Origem

1981: Apresentação de Smalltalk na ITT Research Laboratory

Artigo sobre Smalltalk-80 na Byte Magazine

Se mudam para Schlumberger Research Labs

Tom Love adquire licença do Smalltalk-80

Se torna o primeiro cliente comercial

Cox e Love aprendem Smalltalk com a revista, código fonte e suporte

Page 9: Tales@tdc

I could built a Smalltalk pre-processor for C in a couple of weeks: it’s just what we need

Page 10: Tales@tdc

OOPC

1981 - Object Oriented Pre-Processor

ITT Research Laboratory, junto com Tom Love

sed, awk, compilador C...

1982 - Cox e Love deixam a Schlumberger Research Labs

Fundam a Productivity Products International (PPI)

Renomeada para StepStone (após investimento de VC)

Page 11: Tales@tdc

Objective -C - Primeira versão

1982 - Desenvolvimento do pre-compilador

lex/yacc

1983 - Inicio da comercialização do Objective-C

Adiciona algumas bibliotecas de classes

1986 - Lançado Object Oriented Programming - An evolutionary approach

Page 12: Tales@tdc

About that time Bjarne [Stroustrup] heard about our work and invited me to speak at Bell Labs, which was when I learned he was working on C++. Entirely different notions of what object-oriented meant. He wanted a better C (silicon fab line). I wanted a better way of soldering together components originally fabricated in C to build larger-scale assemblies.

http://moourl.com/89918

‘Concorrência” com C++

Page 13: Tales@tdc

Primeira aparição da Apple

Apple é uma da primeiras interessadas no Objective-C

Além de Clascal, Object Pascal, Dylan*

“They did like PPI/Stepstone because we did such a good job finding errors in their C compiler!"

https://www.youtube.com/watch?v=mdhl0iiv478

Page 14: Tales@tdc

NeXT

1985 - Jobs deixa a Apple e funda a NeXT

NeXT “vai as compras” de tecnologia

1988 - NeXT licencia uso de Objective-C da Stepstone

NeXTStep (OS) e o OpenStep (APIs)

Application Kit e Foundation Kit

Protocolos (conceito, mas não implementação, de herança multipla)

Page 15: Tales@tdc

Objective-C open source

1988 - NeXT adiciona suporte ao GCC

Mas não liberam AppKit e Foundation

1992 - GNUStep: primeira implementação GPL incluindo runtime e libs

1993 - GNU Objective-C runtime

Page 16: Tales@tdc

NeXT adquire Objective-C

1995 - NeXT adquire marcas e direitos do Objective-C

Vende de volta licença de uso para Stepstone

http://moourl.com/89918

Page 17: Tales@tdc

Apple adquire NeXT

1996 - Apple adquire NeXT

Usa NeXTStep como base para criar o Mac OS X

Usa a especificação do OpenStep para criar a Cocoa

Anos depois, transforma Project Builder no Xcode

Page 18: Tales@tdc

Objective-C 2.0

Anunciado na WWDC 2006

Garbage Collector (apenas no Mac OS X)

Melhorias de sintaxe

Melhorias no runtime

Suporte 64 bits

Disponibilizado no Mac OS X 10.5 (Leopard) em 2007

Page 19: Tales@tdc

Objective-C 2.0

Melhorias na sintaxe

@property e @synthesize (ou @dynamic)

Protocolos com @optional e @required

Dot Syntax

Fast enumeration

Extensões de classe

Page 20: Tales@tdc

@property e @synthesize - Antes@interface Person : NSObject { // instance variables NSString *_name;}- (NSString*)name;- (void)setName:(NSString*)aName;@end

@implementation Person- (NSString*)name { return _name;}- (void)setName:(NSString *)aName { if (aName != _name) { [_name release]; } _name = [aName retain];}@end

Page 21: Tales@tdc

@property e @synthesize - Depois@interface Person : NSObject@property (retain) NSString *name;

@end

@implementation Person@synthesize name;

@end

Page 22: Tales@tdc

Atributos para @property

Variáveis de instância publicas (@private e @protected)

Acesso: readonly (gera apenas o getter)

Semantica de armazenamento: assign, copy e retain

Thread safe: nonatomic

Permite nomear o getter

Page 23: Tales@tdc

Atributos e getter nomeado@interface Person : NSObject {@private int age;@protected BOOL active;}@property (retain) NSString *name;@property (assign) int age;@property (assign, getter = isActive) BOOL active;@end

@implementation Person@synthesize name = _name;- (void)doSomething { Person *aPerson = [[Person alloc] init]; if ([aPerson isActive]) { [aPerson setActive:NO]; }}@end

Page 24: Tales@tdc

@property e @synthesize

Key Value Coding:

NSString *name = [person valueForKey:@"name"];

[person setValue:@"Tales" forKey:@"name"];

Page 25: Tales@tdc

Dot notation

Inicialmente, envio de mensagem era feito através de @property (retain) NSString *name;

[person name];

[person setName:@”Tales”];

Com Dot notation, é possível usarNSString *name = person.name;

person.name = @"John";

Ainda é enviada mensagem

Page 26: Tales@tdc

Dot notation

Permite “aberrações”NSMutableArray *mutableArray = NSArray.alloc.init.mutableCopy;

Envio de mensagem pode causar problemas de performance

Sobre-uso (@property vs métodos) Person *p = [[Person alloc] init]; NSArray *thePeople = [NSArray arrayWithObject:p]; NSInteger numberOfPersons = thePeople.count;

Page 27: Tales@tdc

Fast enumaration - Antes

Usando NSEnumerator@interface Person : NSObject@property (retain) NSString *name;@property (assign) int age;@end

@implementation Person- (void)doSomething { NSArray *thePeople = [NSArray array]; // Using NSEnumerator NSEnumerator *enumerator = [thePeople objectEnumerator]; Person *p; while ((p = [enumerator nextObject]) != nil) { NSLog(@"%@ is %i years old.", [p name], [p age]); }}@end

Page 28: Tales@tdc

Fast enumaration - Antes

Usando indices@interface Person : NSObject@property (retain) NSString *name;@property (assign) int age;@end

@implementation Person- (void)doSomething { NSArray *thePeople = [NSArray array]; // Using indexes for (int i = 0; i < [thePeople count]; i++) { Person *p = [thePeople objectAtIndex:i]; NSLog(@"%@ is %i years old.", [p name], [p age]); }}@end

Page 29: Tales@tdc

Fast enumaration - Depois

@interface Person : NSObject@property (retain) NSString *name;@property (assign) int age;@end

@implementation Person- (void)doSomething { NSArray *thePeople = [NSArray array]; // Using fast enumeration for (Person *p in thePeople) { NSLog(@"%@ is %i years old.", [p name], [p age]); }}@end

Page 30: Tales@tdc

Modern Objective-C

Xcode 4 - Apple troca GCC por LLVM

Automatic Reference Counting

Blocks

Literais

@property com @synthesize padrão

NSDictionary e NSArray subscripting

iVar no bloco @implementation

Page 31: Tales@tdc

Blocks

Adição ao C (e por extensão, ao Objective-C e ao C++) ainda não padronizada

Sintaxe inspirada em expressões lambda para criação de closures

OS X 10.6+ e iOS 4.0+

Bibliotecas de terceiros permitem OS X 10.5 e iOS 2.2+

Foco no uso com GCD

Page 33: Tales@tdc

Literais - antes

NSNumber *number = [NSNumber numberWithInt:0];NSArray *array = [NSArray arrayWithObjects:@"nome", @"sobrenome", nil];NSDictionary *dict = [NSDictionary dictionaryWithObjects:@"Tales", @"Pinheiro" forKeys:@"nome", @"sobrenome"];

Page 34: Tales@tdc

Literais - depois

NSNumber *number = @0;NSArray *array = @[@"nome", @"sobrenome"];NSDictionary *dict = @{@"nome": @"Tales", @"sobrenome": @"Pinheiro"};

Page 35: Tales@tdc

Default @synthesize

Não é mais necessário o @synthesize para uma @property

Compilador/runtime declaram automagicamente, equivalente a

@synthesize name = _name;

Page 36: Tales@tdc

Subscripting

LLVM 4.0 ou posterior

Transforma id object1 = [someArray objectAtIndex:0]; id object2 = [someDictionary objectForKey:@"key"]; [someMutableArray replaceObjectAtIndex:0 withObject:object3]; [someMutableDictionary setObject:object4 forKey:@"key"];}

Em id object1 = someArray[0]; id object2 = someDictionary[@"key"]; someMutableArray[0] = object3; someMutableDictionary[@"key"] = object4;

Page 37: Tales@tdc

Subscripting

Custom classes também permitem

Indexada:- (id)objectAtIndexedSubscript:(NSUInteger)idx;

- (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx;

Por chave:- (id)objectForKeyedSubscript:(id <NSCopying>)key;

- (void)setObject:(id)obj forKeyedSubscript:(id <NSCopying>)key;

Page 38: Tales@tdc

Subscripting

É poder (http://nshipster.com/object-subscripting/)

Permite criação de DSLroutes[@"GET /users/:id"] = ^(NSNumber *userID){

// ... }

id piece = chessBoard[@"E1"]; NSArray *results = managedObjectContext[@"Product WHERE stock > 20"];

“Com grandes poderes vêm grandes responsabilidades” BEN, Tio

Page 39: Tales@tdc

O futuro

Módulos! Yay \o/

http://llvm.org/devmtg/2012-11/Gregor-Modules.pdf

http://clang.llvm.org/docs/Modules.html

Já disponível no Clang 3.4 (C e C++)

Headers são frageis e adicionam peso ao compilador

Page 40: Tales@tdc

A fragilidade dos Headers

#define FILE "MyFile.txt"#include <stdio.h>int main() { printf(“Hello, world!\n”);}

Page 41: Tales@tdc

A fragilidade dos Headers

#define FILE "MyFile.txt"// stdio.htypedef struct { //...} FILE;// on and on...

int main() { printf(“Hello, world!\n”);}

Page 42: Tales@tdc

A fragilidade dos Headers

#define FILE "MyFile.txt"// from stdio.htypedef struct { //...} “MyFile.txt”;// on and on...

int main() { printf(“Hello, world!\n”);}

Page 43: Tales@tdc

Tamanho dos headers

#include <stdio.h>int main() { printf(“Hello, world!\n”);}

#include <iostream>int main() { std::cout << “Hello, world!”}

C C++

Fonte

Headers

64 81

11.072 1.161.003

Page 44: Tales@tdc

Módulos

import std; //#include <stdio.h>int main() { printf(“Hello, World!\n”);}

import permite adicionar um módulo nomeadoIgnora macros de pre-processador

Page 45: Tales@tdc

Módulos

import std.stdio;int main() { printf(“Hello, World!\n”);}

import permite modo seletivo

Page 46: Tales@tdc

Módulos

Vejam sessão 404 da WWDC 2013

Page 47: Tales@tdc

Obrigado :D