Reading and Saving an Array of Structures with Objective-C


Today I’m reading a good book called Pragmatic Programmer, and in this book there are some challenges. One is about how to save a simple “data base” record using binary data in you preferred programming language, so I decided do this using Objective>-C. The challenge is very simple, it involves to write a name and a phone number of your contacts.

For me to acomplish this task,  I need to create a structure comprised of two fields (name and phone). See code bellow:

typedef struct
  char name[255];
  char phone[11];
} User;

Now, you must create a vector of User and populate it.

User users[2] = {
  {"Sergio Vieira>\0", "(00)123456\0"},
  {"Alexandra Vieira\0", "(01)987654\0"}

After that, you must to create a  NSData object which is typically used for data storage.

NSData *data = [NSData dataWithBytes:&users length:sizeof(users)];

The method dataWithBytes:lenght creates and returns a data object containing a given number of bytes copied from a given buffer (Reference).

To write the contact list I decided to use a NSUserDefaults class which provide us a interface to easily save data in the system.

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

[userDefaults setObject:data forKey:@"users"];
[userDefaults synchronize];

The methods setObject:forKey: sets the value of the specified default key in the standard application domain (Reference)

With this, all data is saved. To read the sctructure you must to load NSData using NSUserDefaults.

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSData *data = [userDefaults objectForKey:@"users"];
User records[2];

[data getBytes:&records length:sizeof(records)];

and now you can show all stored values.

for (NSUInteger i = 0; i < 2; i++)
  printf("Name:%s Phone:%s\n", records[i].name, records[i].phone);

That’s all. 🙂


Deixe um comentário

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do

Você está comentando utilizando sua conta Sair /  Alterar )

Foto do Google+

Você está comentando utilizando sua conta Google+. Sair /  Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair /  Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair /  Alterar )


Conectando a %s