Posted: fevereiro 18th, 2009 | Author: Carlan Calazans | Tags: aprendizado, dev, iphone, mac, objectivec, ubuntu | 6 Comments »
Objective-C pode ser considerado um cinto de utilidades baseado no C. Isso significa que todo o poder da linguagem pai está disponível, incluindo as diversas bibliotecas. Em todos os meus testes, quando precisei de tipos numéricos usei os tipos primitivos do C. A pouco tempo descobri que existe um problema nessa abordagem.

4 8 15 16 23 42
Dependendo do uso, acredito que os tipos numéricos do C sejam mais indicados, mas ao desenvolver utilizando algumas classes, como NSArray onde não podemos incluir elementos que não sejam objetos, a coisa começa a complicar. O problema em questão não é a linguagem ou os seus criadores e sim a falta de conhecimento do programador.
Olhando a documentação, depois de uma boa garimpada, é possível encontrar referências que chamam atenção. NSNumber (subclasse de NSValue), NSInteger, NSUInteger. A primeira é a mais utilizada e é uma classe (imutável), o resto são somente sinônimos (typedef) para os tipos numéricos já conhecidos do C. Podemos criar um objeto da classe NSNumber através dos tipos signed (ou unsigned) char, short int, int, long int, float, double e BOOL.
Exemplos:
int i
= 123;
float f
= 123.45;
char c
= 'c';
NSNumber * intObject
= [NSNumber numberWithInt
:i
];
NSNumber * floatObject
= [NSNumber numberWithFloat
:f
];
// isn't useful to me
NSNumber * yesObject
= [NSNumber numberWithBool
:YES];
NSNumber * noObject
= [NSNumber numberWithBool
:NO];
NSNumber * doubleObject
= [NSNumber numberWithDouble
:123.456];
NSNumber * charObject
= [NSNumber numberWithChar
:c
];
NSLog
(@"intObject class = %@",
[intObject className
]);
NSLog
(@"floatObject class = %@",
[floatObject className
]);
NSLog
(@"yesObject class = %@",
[yesObject className
]);
NSLog
(@"noObject class = %@",
[noObject className
]);
NSLog
(@"doubleObject class = %@",
[doubleObject className
]);
NSLog
(@"CharObject class = %@",
[charObject className
]);
// string representation
NSLog
(@"\n");
NSLog
(@"String value of intObject = %@",
[intObject stringValue
]);
NSLog
(@"String value of floatObject = %@",
[floatObject stringValue
]);
NSLog
(@"String value of yesObject = %@",
[yesObject stringValue
]);
NSLog
(@"String value of noObject = %@",
[noObject stringValue
]);
NSLog
(@"String value of doubleObject = %@",
[doubleObject stringValue
]);
NSLog
(@"String value of CharObject = %@",
[charObject stringValue
]);
// comparing
// the return will be NSOrderedAscending (greated than), NSOrderedSame (equal to)
// and NSOrderedDescending (less than).
[intObject compare
:floatObject
];
[floatObject compare
:intObject
];
Posted: fevereiro 6th, 2009 | Author: Carlan Calazans | Tags: aprendizado, dev, iphone, mac, objectivec | No Comments »
Quando falamos de String em Objective-C estamos nos referindo as classes NSString e NSMutableString. Como no C, Strings são basicamente um array de caracteres Unicode.

String Theory from xkcd.com
Por que duas classes?
A diferença entre elas é que uma é imutável ( NSString ) e a outra ( NSMutableString ) pode ser modificada. No entanto, é possível atribuir uma nova string em um ponteiro para a classe NSString. Dito isso, fica claro distinguir quando usar as classes mencionadas.
Abaixo temos pedaços de códigos com algumas (não todas) operações disponíveis.
// creation
NSString *firstName
= @"Carlan";
NSString *lastName
= [NSString string];
// or [[NSString alloc] init]
lastName
= @"Calazans";
char cStr
[15] = "An old C string";
NSString *cString
= [NSString stringWithCString
:cStr
];
NSMutableString *fullNameMutable
= [firstName mutableCopy
];
// interpolation
NSString *fullName
= [NSString stringWithFormat
:@"%@ %@", firstName, lastName
];
NSLog
(@"My name is: %@", fullName
);
printf("%s",
[fullName cString
]);
// basic operations
//[firstName appendString:@" Calazans"]; // wont compile
[fullNameMutable appendString
:lastName
];
[fullNameMutable lowercaseString
];
[fullNameMutable uppercaseString
];
[fullNameMutable capitalizedString
];
[fullNameMutable length
];
[fullName writeToFile
:@"/tmp/test.txt" atomically
: YES];
[fullNameMutable replaceString
:@"Carlan" withString
:@"Alan"];
NSRange r
= NSMakeRange
(0,
4);
// NSRange is not a class!
[fullNameMutable substringWithRange
:r
];
[fullNameMutable substringToIndex
:4];
[fullNameMutable substringFromIndex
:4];
NSMutableString *stringWithSpaces
= [@" my string " mutableCopy
];
[stringWithSpaces trimLeadSpaces
];
[stringWithSpaces trimTailSpaces
];
[stringWithSpaces trimSpaces
];
NSString *strA
= @"stringA";
NSString *strB
= @"stringB";
[string1 compare
:string2
];
[string1 caseInsensitiveCompare
:string2
];
NSString *splitMe
= @"carlan:calazans:29:brasileiro";
[splitMe componentsSeparatedByString
:@":"];
Procurei deixar bem poucos comentários para não sujar muito o código. Não fica tão complicado de ler por que o nome dos métodos já dizem o que eles fazem.
Posted: fevereiro 4th, 2009 | Author: Carlan Calazans | Tags: aprendizado, dev, mac, objectivec, ubuntu | No Comments »
Desde ontem estava tentando pegar o conteúdo de uma url qualquer e imprimir no console. Até que não é tão complicado comparando com Ruby ou Python. Minha maior dificuldade foi converter de NSMutableData para NSString. Também não sei por que cargas d’águas não está funcionando para todas as urls, a do google, por exemplo.
Estou gostando de Objective-C, mas sinto falta das facilidades de Ruby e Python, provavelmente por estar mais acostumado a elas. E é muito fácil se perder na chamada a métodos utilizando a sintaxe dos colchetes, pior se eles estiverem aninhados. Como estou programando utilizando o ubuntu a “dot-syntax” não está disponível, acredito que somente no Mac Os. É nessa hora que um bom editor de textos faz toda a diferença.
Pra quem se interessar, segue o código.
#import <Foundation/Foundation.h>
// 03-02-2009
// Carlan Calazans (carlancalazans at gmail.com)
//connection.h
@interface Connection
: NSObject
{
NSString *strUrl;
NSMutableData *myReceivedData;
}
-(void) initialize;
@end
//connection.m
@implementation Connection
-(void) initialize
{
NSLog
(@"Started...");
strUrl
= [NSString stringWithFormat
:@"http://carlancalazans.com"];
NSLog
(@"URL: %@", strUrl
);
myReceivedData
= [[NSMutableData dataWithContentsOfURL
:[NSURL URLWithString
:strUrl
]] autorelease
];
NSLog
(@"Received %d bytes of data.",
[myReceivedData length
]);
NSString *content
= [[NSString alloc
] initWithData
:myReceivedData encoding
:NSUTF8StringEncoding
];
NSLog
(@"Content received: %@", content
);
NSLog
(@"Finished...");
[content release
];
}
@end
//main.m
int main
(int argc,
const char *argv
[])
{
NSAutoreleasePool *pool
= [[NSAutoreleasePool alloc
] init
];
Connection
*con
= [[Connection alloc
] init
];
[con initialize
];
[con release
];
[pool release
];
return 0;
}
Posted: janeiro 29th, 2009 | Author: Carlan Calazans | Tags: dev, iphone, mac, objectivec, ubuntu | No Comments »
Após ter lido alguns how-to’s aqui e ali, resolvi testar. Segui os seguintes passos:
sudo apt-get install gnustep gobjc gnustep-make libgnustep-base-dev
gnustep-netclasses gnustep-dl2
sudo chmod +x /usr/share/GNUstep/Makefiles/GNUstep.sh
Editei o ~/.bashrc e adicionei no final do arquivo:
#gnustep
GNUSTEP_ROOT=/usr/share/GNUstep
export GNUSTEP_ROOT
source $GNUSTEP_ROOT/Makefiles/GNUstep.sh
E agora eu consigo fazer isto:
dog.m
#import <Foundation/NSObject.h>
#import <stdio.h>
// 29-01-2009
// Carlan Calazans (carlancalazans at gmail.com)
// dog.h
@interface Dog
: NSObject
{
// instance variables
}
-(void) bark;
-(void) eat;
-(void) chaseCat;
@end
// dog.m
@implementation Dog
-(void) bark
{
printf("Ruff, ruff, ruff...\n");
}
-(void) eat
{
printf("Im hungry, i love dog food.\n");
}
-(void) chaseCat
{
printf("I think i saw a pussy cat.\n");
}
@end
// main.m
int main
( int argc,
const char *argv
[] )
{
Dog
*zorro
= [[Dog alloc
] init
];
[zorro chaseCat
];
[zorro bark
];
[zorro eat
];
[zorro release
];
return 0;
}
Compilar com o gcc e rodar