SlideShare a Scribd company logo
1 of 47
Download to read offline
Objective-C
Um pouco de arqueologia
Tales Pinheiro
@talesp, tales@newtlabs.com
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
Analyticlal Engine Order Code
CPC Building Scheme
Boehm Unnamed Coding system
Sequentielle Formelübersetzung
40s - Primeiras linguagens
Fortran
Speedcoding
Laning and Zieler
IT
Algol
Simula
CPL
Primeiras linguagens “Modernas”
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 usar
NSString *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 DSL
routes[@"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.h
typedef struct {
//...
} FILE;
// on and on...
int main() {
printf(“Hello, world!n”);
}
A fragilidade dos Headers
#define FILE "MyFile.txt"
// from stdio.h
typedef 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 nomeado
Ignora 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

More Related Content

What's hot

What's hot (10)

Understanding the Python GIL
Understanding the Python GILUnderstanding the Python GIL
Understanding the Python GIL
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
 
Mastering Python 3 I/O
Mastering Python 3 I/OMastering Python 3 I/O
Mastering Python 3 I/O
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible Java
 
Mastering Python 3 I/O (Version 2)
Mastering Python 3 I/O (Version 2)Mastering Python 3 I/O (Version 2)
Mastering Python 3 I/O (Version 2)
 
rake puppetexpert:create - Puppet Camp Silicon Valley 2014
rake puppetexpert:create - Puppet Camp Silicon Valley 2014rake puppetexpert:create - Puppet Camp Silicon Valley 2014
rake puppetexpert:create - Puppet Camp Silicon Valley 2014
 
Py conkr 20150829_docker-python
Py conkr 20150829_docker-pythonPy conkr 20150829_docker-python
Py conkr 20150829_docker-python
 
Rust vs C++
Rust vs C++Rust vs C++
Rust vs C++
 
Beyond javascript using the features of tomorrow
Beyond javascript   using the features of tomorrowBeyond javascript   using the features of tomorrow
Beyond javascript using the features of tomorrow
 
Generator Tricks for Systems Programmers, v2.0
Generator Tricks for Systems Programmers, v2.0Generator Tricks for Systems Programmers, v2.0
Generator Tricks for Systems Programmers, v2.0
 

Viewers also liked (9)

RubyistのためのObjective-C入門
RubyistのためのObjective-C入門RubyistのためのObjective-C入門
RubyistのためのObjective-C入門
 
よくわかるオンドゥル語
よくわかるオンドゥル語よくわかるオンドゥル語
よくわかるオンドゥル語
 
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみたスマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
 
Defnydd trydan Ysgol y Frenni
Defnydd trydan Ysgol y FrenniDefnydd trydan Ysgol y Frenni
Defnydd trydan Ysgol y Frenni
 
Method Shelters : Another Way to Resolve Class Extension Conflicts
Method Shelters : Another Way to Resolve Class Extension Conflicts Method Shelters : Another Way to Resolve Class Extension Conflicts
Method Shelters : Another Way to Resolve Class Extension Conflicts
 
Romafs
RomafsRomafs
Romafs
 
Beginning to iPhone development
Beginning to iPhone developmentBeginning to iPhone development
Beginning to iPhone development
 
Objective-C Survives
Objective-C SurvivesObjective-C Survives
Objective-C Survives
 
Présentation gnireenigne
Présentation   gnireenignePrésentation   gnireenigne
Présentation gnireenigne
 

Similar to Tales@tdc

Objective c
Objective cObjective c
Objective c
Stijn
 
Topic2JavaBasics.ppt
Topic2JavaBasics.pptTopic2JavaBasics.ppt
Topic2JavaBasics.ppt
MENACE4
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS Basics
Petr Dvorak
 

Similar to Tales@tdc (20)

Objective c intro (1)
Objective c intro (1)Objective c intro (1)
Objective c intro (1)
 
Objective-C talk
Objective-C talkObjective-C talk
Objective-C talk
 
Modernizes your objective C - Oliviero
Modernizes your objective C - OlivieroModernizes your objective C - Oliviero
Modernizes your objective C - Oliviero
 
Objective c
Objective cObjective c
Objective c
 
Objective c
Objective cObjective c
Objective c
 
iOS Session-2
iOS Session-2iOS Session-2
iOS Session-2
 
Topic2JavaBasics.ppt
Topic2JavaBasics.pptTopic2JavaBasics.ppt
Topic2JavaBasics.ppt
 
hallleuah_java.ppt
hallleuah_java.ppthallleuah_java.ppt
hallleuah_java.ppt
 
2.ppt
2.ppt2.ppt
2.ppt
 
MFF UK - Introduction to iOS
MFF UK - Introduction to iOSMFF UK - Introduction to iOS
MFF UK - Introduction to iOS
 
Big Data, Data Lake, Fast Data - Dataserialiation-Formats
Big Data, Data Lake, Fast Data - Dataserialiation-FormatsBig Data, Data Lake, Fast Data - Dataserialiation-Formats
Big Data, Data Lake, Fast Data - Dataserialiation-Formats
 
FI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS BasicsFI MUNI 2012 - iOS Basics
FI MUNI 2012 - iOS Basics
 
JAVA BASICS
JAVA BASICSJAVA BASICS
JAVA BASICS
 
iPhone Development Intro
iPhone Development IntroiPhone Development Intro
iPhone Development Intro
 
Ontopia tutorial
Ontopia tutorialOntopia tutorial
Ontopia tutorial
 
Modernize your Objective-C
Modernize your Objective-CModernize your Objective-C
Modernize your Objective-C
 
iOS,From Development to Distribution
iOS,From Development to DistributioniOS,From Development to Distribution
iOS,From Development to Distribution
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 

More from Tales Andrade (8)

Debugging tips and tricks - coders on beers Santiago
Debugging tips and tricks -  coders on beers SantiagoDebugging tips and tricks -  coders on beers Santiago
Debugging tips and tricks - coders on beers Santiago
 
Delegateless Coordinators - take 2
Delegateless Coordinators - take 2Delegateless Coordinators - take 2
Delegateless Coordinators - take 2
 
Delegateless Coordinator
Delegateless CoordinatorDelegateless Coordinator
Delegateless Coordinator
 
Swift na linha de comando
Swift na linha de comandoSwift na linha de comando
Swift na linha de comando
 
Debugging tips and tricks
Debugging tips and tricksDebugging tips and tricks
Debugging tips and tricks
 
Usando POP com Programação Funcional
Usando POP com Programação FuncionalUsando POP com Programação Funcional
Usando POP com Programação Funcional
 
Swift!.opcionais.oh!.my()?!?
Swift!.opcionais.oh!.my()?!?Swift!.opcionais.oh!.my()?!?
Swift!.opcionais.oh!.my()?!?
 
Debugging fast track
Debugging fast trackDebugging fast track
Debugging fast track
 

Recently uploaded

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Recently uploaded (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 

Tales@tdc

  • 1. Objective-C Um pouco de arqueologia Tales Pinheiro @talesp, tales@newtlabs.com
  • 2. 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
  • 4. Analyticlal Engine Order Code CPC Building Scheme Boehm Unnamed Coding system Sequentielle Formelübersetzung 40s - Primeiras linguagens
  • 7. 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
  • 8. 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
  • 9. I could built a Smalltalk pre-processor for C in a couple of weeks: it’s just what we need
  • 10. 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)
  • 11. 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
  • 12. 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++
  • 13. 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
  • 14. 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)
  • 15. 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
  • 16. 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
  • 17. 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
  • 18. 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
  • 19. 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
  • 20. @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
  • 21. @property e @synthesize - Depois @interface Person : NSObject @property (retain) NSString *name; @end @implementation Person @synthesize name; @end
  • 22. 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
  • 23. 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
  • 24. @property e @synthesize Key Value Coding: NSString *name = [person valueForKey:@"name"]; [person setValue:@"Tales" forKey:@"name"];
  • 25. 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 usar NSString *name = person.name; person.name = @"John"; Ainda é enviada mensagem
  • 26. 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;
  • 27. 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
  • 28. 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
  • 29. 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
  • 30. 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
  • 31. 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
  • 33. Literais - antes NSNumber *number = [NSNumber numberWithInt:0]; NSArray *array = [NSArray arrayWithObjects:@"nome", @"sobrenome", nil]; NSDictionary *dict = [NSDictionary dictionaryWithObjects:@"Tales", @"Pinheiro" forKeys:@"nome", @"sobrenome"];
  • 34. Literais - depois NSNumber *number = @0; NSArray *array = @[@"nome", @"sobrenome"]; NSDictionary *dict = @{@"nome": @"Tales", @"sobrenome": @"Pinheiro"};
  • 35. Default @synthesize Não é mais necessário o @synthesize para uma @property Compilador/runtime declaram automagicamente, equivalente a @synthesize name = _name;
  • 36. 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;
  • 37. 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;
  • 38. Subscripting É poder (http://nshipster.com/object-subscripting/) Permite criação de DSL routes[@"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
  • 39. 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
  • 40. A fragilidade dos Headers #define FILE "MyFile.txt" #include <stdio.h> int main() { printf(“Hello, world!n”); }
  • 41. A fragilidade dos Headers #define FILE "MyFile.txt" // stdio.h typedef struct { //... } FILE; // on and on... int main() { printf(“Hello, world!n”); }
  • 42. A fragilidade dos Headers #define FILE "MyFile.txt" // from stdio.h typedef struct { //... } “MyFile.txt”; // on and on... int main() { printf(“Hello, world!n”); }
  • 43. 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
  • 44. Módulos import std; //#include <stdio.h> int main() { printf(“Hello, World!n”); } import permite adicionar um módulo nomeado Ignora macros de pre-processador
  • 45. Módulos import std.stdio; int main() { printf(“Hello, World!n”); } import permite modo seletivo