Most of the time we see in tutorials, code examples and even apple starter project our view controller being the delegate and the datasource of some tableview. Although I’m not saying this approach is wrong, it is not the best for every situation, and even in the worst cases we most of the time use this approach. As an example, if our viewcontroller has two tableviews, generally we see a lot of if code to control the logic for each tableview. Even, when we got only one tableview, but this table can be ordered, sorted, searched, and displayed in different formats, our code gets full of if codes. This can lead to a huge amount of bugs, work-arounds and finally to an confused and impossible code to maintain.

In those cases we can always use our good OOP (object orientation programming) knowledge.

Objective-C has a very good design pattern called “Delegate”. In this pattern you delegate some functions to another class to execute. In IOS development we use delegates all the time. But the delegate of a tableview does not necessary need to be the viewcontroller container of the tableview. We can create other NSObject classes to be the delegate for a tableview.

“But what kind of benefits do i get doing that?” you must be thinking. Well, using this pattern you can create a different delegate for each state of your table.

In in the state1 your tableview does not have sections and your cells should only display text, you create a delegate for that.

And if in the state2 your tableview should have sections, and each row should display also a detail for each row, you don’t need to create a lot of ifs. Just create another delegate, assign it as the new delegate for you tableview, and call the reloadData message of your tableview. Ad you are done.

Here goes an example of two datasources delegators:

Continuar Lendo »

Often i need to use some image as a background for many visual components, like views, scrollviews, buttons, other images… and most of time i ended using a large enough image to cover the front image.

So, if my view was 1000×700 i needed to load an 1000×700 image for the background. But this image will eat a lot of memory just to be there as a background. There should be a better way to do this. And there is a better way to do this.

All you have to do is create your UIImage like this

UIImage* backgroundImage = [[UIImage imageNamed:@”stretchableImage.png”] stretchableImageWithLeftCapWidth:44 topCapHeight:45];

this stretchableImageWithLeftCapWidth specify how many pixel in the left must be kept. The same goes to the topCapHeight, and in this case it specifies the number of pixels in the top.

So in the example, the sdk will keep the first 44 pixels, copy the 45th along all the way of the image, and in the end keep again the last 44 pixels. It will do the same for the height.

So you wont need to keep a large image in memory. And you can also use this technique to create dynamic buttons, views and anything that you may even not know how length it is.

Here you can find an image as example (but keep in mind that as a designer, i’m a good programmer ^_^” )

Visit my tumblr for more iphone tips and tricks

iOS – Parsing JSON

Very often we need to access some kind of service available on the internet to gather some data to work with. Most of nowadays services prefer to send data using the JSON format (learn more about json here). It’s simple and compared to XML, smaller.

In iOS there is no native way to work with json text, but there are some great library avaliable out there that make the job really easy. One of the best I know is the TouchJSON (a wiki about it is avaliable here). This library makes really simple the task to parse a JSON string.

Continue reading this on my tumblr

Almost all view controllers need to load some data from the internet and interact with them.

This kind of task may sound simple at first, but as you will find out, there are some kind of complications, like autoreleasing objects with no autorelease pool in place, how to get notified when your data has been loaded and how to handle this data. Also all the updates to the view should be done in the main thread, not the background thread, to avoid possibly app crash.

To solve all these problems I’ve created a subclass of UiViewController that controls all the steps required to load the data the right way, and updates the view the right way.

To read more about this, continue the reading in my tumblr blog

Como usar json com o iphone

Seguindo o tutorial anterior, vamos agora acessar um serviço que retorne a mensagem no formato json e consumir essa mensagem dentro da nossa aplicação.

O serviço escolhido foi a API pública do twitter. Você pode conferir a API completa no site do twitter.

No nosso exemplo vamos recuperar a timeline da minha conta do twitter.

Vamos começar criando uma classe que será responsável por fazer conexões com a internet. Basicamente esta classe terá o método que discutimos no post anterior.

Continuar Lendo »

Para fazer requisições web pelo iPhone é muito simples. Inclusive se for necessário enviar parâmetros, basta usar a parte que está em negrito.

NSURL *url = [NSURL URLWithString:@”http://www.google.com.br”%5D;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@”POST”];
NSData *requestBody = [@”username:x&password:y” dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:requestBody];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];

A variavel requestError, terá a referencia para qualquer erro que possa ocorrer com a conexão.

A variavel responseString terá o texto que retornou do servidor.

No próximo post iremos usar esse método para obter um json e depois realizarmos a tradução do json para um NSDictionary

VIVO - Plataforma de Desenvolvedores

Hoje durante a Campus Party a VIVO lançou a sua plataforma de desenvolvedores. Essa plataforma consite de uma Loja virtual, e de Kits de ferramentas para facilitar o desenvolvimento de aplicativos que utilizem a sua infra-estrutura.

Atualmente apenas a API de envio de SMS está disponível para teste, enquanto que as APIs de MMS e WAP-PUSH estarão disponíveis em breve, de acordo com o site.

Para comercializar os aplicativos a VIVO vai oferecer, a princípio, duas formas de comercialização. Uma para aplicativos “beta” e “demonstrativos” que poderão custar no máximo R$2,00; e outra com aplicativos finalizados, que poderão custar até R$20,00. Esses aplicativos terão que passar por um processo de avaliação bem semelhante ao da AppStore da Apple. Em ambos os casos, para aplicativos baixados do site da loja virtual da VIVO o lucro para o desenvolvedor é de 70% do preço do aplicativo , já para aplicativos enviados via SMS, o desenvolvedor fica com apenas 10% do valor do aplicativo

Continuar Lendo »