Professional Documents
Culture Documents
Objective-C
martes, 7 de abril de 15
OBJETOS
Principios de 1980, Brad Cox y Tom Love deciden agregar los conceptos
de orientacin de objetos al lenguaje C. Para los objetos, los construyeron
sobre la idea de estructuras localizadas en el heap y se le agrega la sintaxis
del envo de mensajes. El resultado fue el lenguaje Objective-C.
Los objetos son muy parlanchines por naturaleza. Ellos envan y reciben
mensajes acerca del trabajo que pueden desempear.
martes, 7 de abril de 15
martes, 7 de abril de 15
MENSAJES
El
El
martes, 7 de abril de 15
MENSAJES
martes, 7 de abril de 15
MENSAJES
Mtodos de clase
Mtodos de instancia
[NSDate date]
[now timeIntervalSince1970]
[now dateByAddingTimeInterval:100000]
martes, 7 de abril de 15
MENSAJES
Es una buena practica (y el nico camino aprobado por Apple) para el envo de mensajes en una
lnea de cdigo (mensajes anidados):
Multiples argumentos.
inUnit:NSMonthCalendarUnit
forDate:now];
Es la mejor manera de escribir un mtodo con multiples argumentos, de otra manera se vera
muy largo. En este caso, el nombre del mtodo es ordinalityOfUnit:inUnit:forDate:
martes, 7 de abril de 15
NSSTRING
martes, 7 de abril de 15
NSARRAY
NSMUTABLEARRAY
martes, 7 de abril de 15
NSARRAY
NSMUTABLEARRAY
Algunos mtodos.
martes, 7 de abril de 15
CLASES
martes, 7 de abril de 15
CLASES (.H)
#import <Foundation/Foundation.h>
@interface Person : NSObject {
float heightInMeters;
int weightInKilos;
}
- (float)heightInMeters;
- (void)setHeightInMeters:(float);
- (int)weightInKilos;
- (void)setWeightInKilos:(int)w;
- (float)bodyMassIndex;
@end
martes, 7 de abril de 15
CLASES (.M)
#import Person.h
@implementation Person
// Metodos de acceso
- (void)setWeightInKilos:(int)w {
- (float)heightInMeters {
return heightInMeters;
heightInMeters = h;
weightInKilos = w;
- (float)bodyMassIndex {
- (int)weightInKilos {
return weightInKilos / (heightInMeters *
heightInMeters);
return weightInKilos;
}
//
- (void)setHeightInMeters:(float)h {
martes, 7 de abril de 15
}
@end
CLASES (IMPLEMENTACIN)
#import <Foundation/Foundation.h>
#import Person.h
@autoreleasepool {
[person setWeightInKilos:96];
[person setHeightInMeters:1.8];
NSLog(@person (%d %d) has a BMI of %f , [person weightInKilos], [person heightInMeters], bmi);
return 0;
martes, 7 de abril de 15
DIAGRAMA DE OBJETOS
martes, 7 de abril de 15
PROPIEDADES
.h
.m
martes, 7 de abril de 15
SELF
Dentro de un mtodo, se tiene acceso a la variable local implcita self. self es un apuntador
al objeto que est ejecutando el mtodo, esto es til cuando se quiere enviar mensajes a el
mismo.
float h = [self heightInMeters];
return [self weightInKilos] / (h * h);
Adems se puede pasar a self como un argumento, dejando a otros objetos conocer donde
est el objeto actual.
- (void)addYourselfToArray:(NSMutableArray *)theArray {
}
martes, 7 de abril de 15
[theArray addObject:self];
HERENCIA
martes, 7 de abril de 15
HERENCIA
martes, 7 de abril de 15
SUSTITUCIN DE MTODOS
(OVERRIDING METHODS)
Cuando
martes, 7 de abril de 15
SUPER
Para
martes, 7 de abril de 15
VARIABLE DE INSTANCIA DE
OBJETO
Una
Object-type
To-one
complejo.
To-many
martes, 7 de abril de 15
#IMPORT Y @CLASS
#import: se
@class: Se
martes, 7 de abril de 15
COLECCIONES
Arreglos, conjuntos y diccionarios
martes, 7 de abril de 15
ORDENAMIENTO
NSMutableArray
- (void)sortUsingDescriptors:(NSArray *)sortDescriptors
El
martes, 7 de abril de 15
NSSORTDESCRIPTOR
martes, 7 de abril de 15
NSSORTDESCRIPTOR
NSSortDescriptor
*voa = [NSSortDescriptor
sortDescriptorWithKey:@valueOfAssets ascending:YES];
NSSortDescriptor
*ei = [NSSortDescriptor
sortDescriptorWithKey:@employeeID ascending:YES];
[employees
sortUsingDescriptors:[NSArray
arrayWithObjects:voa, ei, nil]];
martes, 7 de abril de 15
FILTRADO
Existe una clase llamada NSPredicate, un predicado contiene una sentencia que se podra cumplir.
Un NSMutableArray tiene un mtodo prctico para descartar todos los objetos que no satisfacen
el predicado:
- (void)filterUsingPredicate:(NSPredicate *)predicate;
Un NSArray tiene un mtodo para crear un nuevo arreglo conteniendo todos los objetos que
satisfacen el predicado:
- (NSArray)filteredArrayUsingPredicate:(NSPredicate *)predicate;
martes, 7 de abril de 15
NSSET/NSMUTABLESET
martes, 7 de abril de 15
NSDICTIONARY/
NSMUTABLEDICTIONARY
Un
martes, 7 de abril de 15
martes, 7 de abril de 15
NSNUMBERS
NSNumber
*n1 = @1000;
NSNumber
*n2 = @3.1415926;
NSNumber
*c = @'c';
NSNumber
*b = @YES;
NSNumber
*f = @2.5f;
NSNumber
*nu = @256u;
martes, 7 de abril de 15
CONSTANTES
Para
function-like: Macro
#define MAX(A, B)
martes, 7 de abril de 15
VARIABLES GLOBALES
NSLocale.h
extern NSString const *NSLocaleCurrencyCode;
NSLocale.m
NSString const *NSLocaleCurrencyCode = @currency;
Uso
NSLocale *here = [NSLocale currentLocale];
NSString *currency = [here objectForKey:NSLocaleCurrencyCode];
martes, 7 de abril de 15
ENUM
enum BlenderSpeed {
BlenderSpeedStir = 1,
BlenderSpeedChop = 2,
BlenderSpeedLiquify = 5,
BlenderSpeedPulse = 9,
BlenderSpeedIceCrush = 15,
};
@interface Blender : NSObject {
}
- (void)setSpeed:(BlenderSpeed)x;
@end
martes, 7 de abril de 15
BlenderSpeedStir = 1,
BlenderSpeedChop = 2,
BlenderSpeedLiquify = 5,
BlenderSpeedPulse = 9,
BlenderSpeedIceCrush = 15,
} BlenderSpeed;
@interface Blender : NSObject {
BlenderSpeed speed;
}
- (void)setSpeed:(BlenderSpeed)x;
@end
martes, 7 de abril de 15
ASIGNACIN AUTOMTICA
typedef enum {
BlenderSpeedStir,
BlenderSpeedChop,
BlenderSpeedLiquify,
BlenderSpeedPulse,
BlenderSpeedIceCrush,
} BlenderSpeed;
martes, 7 de abril de 15
martes, 7 de abril de 15
ESCRITURA DE ARCHIVO
CON NSSTRING
NSMutableString *str = [[NsMutableString alloc] init];
NSError *error = nil;
Something to str
[str writeToFile:@/tmp/cool.txt
atomically:YES
encoding:NSUTF8StringEncoding
error:&error];
martes, 7 de abril de 15
martes, 7 de abril de 15
ESCRIBIR UN NSDATA A UN
ARCHIVO
BOOL written = [data writeToFile:@/tmp/google.png
options:0
error:&error];
martes, 7 de abril de 15
martes, 7 de abril de 15
CALLBACKS
martes, 7 de abril de 15
CALLBACKS
martes, 7 de abril de 15
PROTOCOLOS
martes, 7 de abril de 15
SINTAXIS PROTOCOLO
@protocol ProtocoName <NSObject>
@optional
// list of methods and properties
@required
// list of methods and properties
@end
martes, 7 de abril de 15
SUSCRIPCIN A UN
PROTOCOLO
@inteface MyClass : NSObject <MyProtocol,
AnotherProtocol, YetAnotherProtocol>
@end
martes, 7 de abril de 15
PROPERTY LIST
NAArray
NSDictionary
NSString
NSData
NSDate
NSNumber
martes, 7 de abril de 15
PROPERTY LIST
#import <Foundation/Foundation.h>
[stock setObject:@GOOG
forKey:@symbol];
@autoreleasepool {
init];
forKey:@shares];
[stocks addObject:stock];
NSMutableDictionary *stock;
stock = [NSMutableDictionary dictionary];
[stocks writeToFile:@/tmp/stocks.plist
[stock setObject:@AAPL
atomically:YES];
forKey:@symbol];
martes, 7 de abril de 15
return 0;
}
PROPERTY LIST
martes, 7 de abril de 15
PROPERTY LIST
<?xml version=1.0 encoding=UTF-8?>
<dict>
<dict>
<key>shares</key>
<plist versin=1.0>
<integer>160</integer>
<array>
<key>symbol</key>
<string>GOOG</string>
<dict>
<key>shares</key>
<integer>200</integer>
</array>
<key>symbol</key>
</plist>
<string>AAPL</string>
martes, 7 de abril de 15
<dict>
En la clase NSObject existe un mtodo init. Despus de asignar espacio para un objeto, se enva el
mensaje init a la nueva instancia para poder inicializar sus variables de instancia con los valores utilizables.
- (id)init {
self =[super init];
if (self) {
[self setVoltage:120];
}
return self
}
martes, 7 de abril de 15
- (id)init {
return [self initWithProductName:@Unknown];
}
martes, 7 de abril de 15
INICIALIZADOR DESIGNADO
Al
martes, 7 de abril de 15
Reglas que todo programador Objective-C con estilo debe seguir cuando se escribe un
inicializado:
Si una clase tiene muchos inicializadores, slo uno debe hacer el trabajo real. Ese mtodo
es conocido como el inicializador designado. Todos los dems inicializadores deben
llamar, ya sea directa o indirectamente el inicializador designado
martes, 7 de abril de 15
CATEGORAS
Las
1.Crear:
An
objective-C category,
martes, 7 de abril de 15
CATEGORA
martes, 7 de abril de 15
INTRODUCCIN A BLOQUES
Los
En
martes, 7 de abril de 15
DECLARACIN DE UN BLOQUE
martes, 7 de abril de 15
EJEMPLO BLOQUE
int main(int argc, cons char * argv[]) {
@autoreleasepool {
withString:@
[newStrings addObject:newString];
// Asignacin de un bloque a una variable
}; // Fin de la asignacin del bloque
[oldStrings enumerateObjectsUsingBlock:devowelizer];
NSMutableString *newString = [NSMutableString
stringWithString:string];
}
return 0;
for(NSString *s in vowels) {
martes, 7 de abril de 15
DECLARACIN Y
ASIGNACIN DE UN BLOQUE
void (^devowelizer)(id string, NSUInteger i,
BOOL *stop) = ^(id string, NSUInteger i,
BOOL *stop) {
NSMutableString *newString
= [NSMutableString stringWithString:string];
withString:@
options:NSCaseInsensitiveSearch
range:fullRange];
for(NSString *s in vowels) {
NSRange fullRange =
NSMakeRange(0, [newString lenght]);
[newString
replaceOccurrencesOfString:s
martes, 7 de abril de 15
}
[newStrings
addObject:newString];
}; // Fin de la asignacin del bloque
TYPEDEF
ArrayEnumerationBlock devowelizer;
martes, 7 de abril de 15
RETORNO DE VALORES
double (^divBlock)(double,double) = ^(double k, double j) {
return k/j;
};
martes, 7 de abril de 15
PATRONES DE DISEO DE
SOFTWARE
martes, 7 de abril de 15
PATRONES DE DISEO
martes, 7 de abril de 15
PATRONES DE DISEO
martes, 7 de abril de 15
MODEL-VIEW-CONTROLLER
Modelo:
Vista:
Controlador:
martes, 7 de abril de 15
DIAGRAMA MVC
martes, 7 de abril de 15
App
UIKit:
Foundation:
martes, 7 de abril de 15
DELEGADO DE LA
APLICACIN
application:didFinishLaunchingWithOptions:
martes, 7 de abril de 15
MVC EN IOS
martes, 7 de abril de 15
LA APLICACIN
martes, 7 de abril de 15
MVC DE LA APLICACIN
martes, 7 de abril de 15
SINGLETON
Asegura
martes, 7 de abril de 15
DIAGRAMA SINGLETON
martes, 7 de abril de 15