Upload
tales-andrade
View
633
Download
1
Embed Size (px)
DESCRIPTION
Citation preview
Objective-CUm pouco de arqueologia
Tales Pinheiro@talesp, [email protected]
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
Charles Babbage
Augusta Ada King
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
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”
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
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
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
I could built a Smalltalk pre-processor for C in a couple of weeks: it’s just what we need
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)
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
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++
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
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)
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
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
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
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
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
@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
@property e @synthesize - Depois@interface Person : NSObject@property (retain) NSString *name;
@end
@implementation Person@synthesize name;
@end
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
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
@property e @synthesize
Key Value Coding:
NSString *name = [person valueForKey:@"name"];
[person setValue:@"Tales" forKey:@"name"];
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
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;
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
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
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
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
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
http://blog.bignerdranch.com/3001-cocoa-got-blocks/http://vimeo.com/68340179
Literais - antes
NSNumber *number = [NSNumber numberWithInt:0];NSArray *array = [NSArray arrayWithObjects:@"nome", @"sobrenome", nil];NSDictionary *dict = [NSDictionary dictionaryWithObjects:@"Tales", @"Pinheiro" forKeys:@"nome", @"sobrenome"];
Literais - depois
NSNumber *number = @0;NSArray *array = @[@"nome", @"sobrenome"];NSDictionary *dict = @{@"nome": @"Tales", @"sobrenome": @"Pinheiro"};
Default @synthesize
Não é mais necessário o @synthesize para uma @property
Compilador/runtime declaram automagicamente, equivalente a
@synthesize name = _name;
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;
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;
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
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
A fragilidade dos Headers
#define FILE "MyFile.txt"#include <stdio.h>int main() { printf(“Hello, world!\n”);}
A fragilidade dos Headers
#define FILE "MyFile.txt"// stdio.htypedef struct { //...} FILE;// on and on...
int main() { printf(“Hello, world!\n”);}
A fragilidade dos Headers
#define FILE "MyFile.txt"// from stdio.htypedef struct { //...} “MyFile.txt”;// on and on...
int main() { printf(“Hello, world!\n”);}
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
Módulos
import std; //#include <stdio.h>int main() { printf(“Hello, World!\n”);}
import permite adicionar um módulo nomeadoIgnora macros de pre-processador
Módulos
import std.stdio;int main() { printf(“Hello, World!\n”);}
import permite modo seletivo
Módulos
Vejam sessão 404 da WWDC 2013
Obrigado :D