I have a simple form that is only taking four fields right now (I'll add in more later)
- First Name
- Last Name
- Home Email
- Work Email
I only want to save items that have a value as a new contact. Right now, if I don't enter in a value, then in the contact page the value is "NULL". What is the appropriate way to handle this?
Here is my code
#pragma mark - Add New Contacts Methods
- (IBAction)savePublicContact:(UIBarButtonItem *)sender {
CFErrorRef anError = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &anError);
ABRecordRef person = ABPersonCreate();
Person *personUserDefined = [self populatePersonToSave];
ABRecordSetValue(person,kABPersonFirstNameProperty,(__bridge CFTypeRef)(personUserDefined.firstName),&anError);
ABRecordSetValue(person,kABPersonLastNameProperty,(__bridge CFTypeRef)(personUserDefined.lastName),&anError);
ABMutableMultiValueRef emailMultiValue = ABMultiValueCreateMutable(kABPersonEmailProperty);
ABMultiValueAddValueAndLabel(emailMultiValue, (__bridge CFTypeRef)(personUserDefined.homeEmail), (CFStringRef)@"Home Email", NULL);
ABMultiValueAddValueAndLabel(emailMultiValue, (__bridge CFTypeRef)(personUserDefined.workEmail), (CFStringRef)@"Work Email", NULL);
ABRecordSetValue(person, kABPersonEmailProperty, emailMultiValue, &anError);
ABAddressBookAddRecord(addressBook, person, &anError);
if(ABAddressBookSave(addressBook, &anError)){
UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Added Contact"
message:@"You successfully added a contact"
delegate:self
cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alertsuccess show];
}else{
UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Contact Error"
message:(@"Contact was not able to be added")
delegate:self
cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alertsuccess show];
}
}
- (Person *)populatePersonToSave
{
Person *person = [[Person alloc] init];
if([self.firstNameToSaveTextField.text length] > 0){
person.firstName = self.firstNameToSaveTextField.text;
}
if([self.lastNameToSaveTextField.text length] > 0) {
person.lastName = self.lastNameToSaveTextField.text;
}
if([self.workEmailToSaveTextField.text length] > 0){
person.workEmail = self.workEmailToSaveTextField.text;
}
if([self.homeEmailToSaveTextField.text length] > 0){
person.homeEmail = self.homeEmailToSaveTextField.text;
}
return person;
}