Storing UIActionSheet data into array in CoreData - core-data

I've got an issue that's been bothering me. I have to store information from a UI Action Sheet in iOS into an array provided in CoreData. Trouble is, the Action Sheet is in a different function than the one used to store the data.
First: Here's the relevant code for storing the data:
(... checking for all fields; working properly)
}
else
{
newContact = [NSEntityDescription insertNewObjectForEntityForName:#"Contacts" inManagedObjectContext:context];
[newContact setValue:Salutation.text forKey:#"Salutation"];
[newContact setValue:FirstName.text forKey:#"FirstName"];
[newContact setValue:LastName.text forKey:#"LastName"];
[newContact setValue:CompanyName.text forKey:#"CompanyName"];
[newContact setValue:EmailAddress.text forKey:#"EmailAddress"];
[newContact setValue:PhoneNumber.text forKey:#"PhoneNumber"];
newContact.Disinfector =[NSNumber numberWithBool:yesWasher];
newContact.Sterilizer =[NSNumber numberWithBool:yesSterilizer];
newContact.CoffeeMaker =[NSNumber numberWithBool:yesCoffeeMaker];
Salutation.text = #"";
FirstName.text = #"";
LastName.text = #"";
CompanyName.text = #"";
EmailAddress.text = #"";
PhoneNumber.text = #"";
yesWasher = YES;
[WasherTog setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateNormal];
yesSterilizer = YES;
[SterilizerTog setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateNormal];
yesCoffeeMaker = YES;
[CoffeeMakerTog setImage:[UIImage imageNamed:#"checked.png"] forState:UIControlStateNormal];
Second, here's the code for the Action Sheet and handling the input:
- (void)showSalutation:(id)sender
{
UIActionSheet *popUp = [[UIActionSheet alloc] initWithTitle:#"Choose Salutation" delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:#"Cancel" otherButtonTitles:#"Mr.", #"Mrs.", #"Ms.", #"Dr.", nil];
popUp.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
[popUp showInView:self.view];
[popUp release];
}
- (void)showSalutation:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
Salutation.text = #"Mr.";
}
else if (buttonIndex == 1)
{
Salutation.text = #"Mrs.";
}
else if (buttonIndex == 2)
{
Salutation.text = #"Ms.";
}
else if (buttonIndex == 3)
{
Salutation.text = #"Dr.";
}
}
I feel like I'm making a lot of newbie mistakes, so please forgive me. I've been learning how to code all weekend and you guys have been my best friend for this stuff. I just haven't seen this particular issue on the net.
Thanks in advance for your help!
Chris

If you are jsut trying to select a string based on the button index use an instance variable. For example you could declare NSString* yourString in the header and use it as follows:
if (button.index == 0) {
yourString = #"Mr."
}
Just following that pattern should work and you can do whatever you want with yourString from there.

Related

Changes to Core Data are not saved when use deletedObjects:entity.attributeName

I am trying to delete the value of some Attributes in two linked Entities. Here is the code I am using:
+ (MeetPhoto *)deletePhotoForSelectedMeet:(MarksFromMeets *)specificMeet
inManagedObjectContext:(NSManagedObjectContext *)context;
{
MeetPhoto *results = nil;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"MarksFromMeets"];
request.predicate = [NSPredicate predicateWithFormat:#"uniqueResultID = %#", specificMeet.uniqueResultID];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"uniqueResultID" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];
if (!matches || [matches count] > 1) {
NSLog(#"There has been an error in matches in %#: \n%#.\n matches count = %lu",
NSStringFromClass([self class]),
NSStringFromSelector(_cmd),
(unsigned long)[matches count]);
} else if ([matches count] == 0){
NSLog(#"There were no matches in %#: \n%#.\n matches count = %lu",
NSStringFromClass([self class]),
NSStringFromSelector(_cmd),
(unsigned long)[matches count]);
} else {
if (debug == 1) NSLog(#"In %# and matches = %lu",NSStringFromClass([self class]),(unsigned long)[matches count]);
for (MarksFromMeets* meetEntity in matches) {
if (debug == 1) NSLog(#" MarksFromMeet = %# \n thumbnail = %# \n photo = %#",meetEntity.meetName,meetEntity.photoThumbNail,meetEntity.whichPhoto.photo);
[context deleteObject:meetEntity.photoThumbNail];
[context deleteObject:meetEntity.whichPhoto.photo];
NSError *mySavingError = nil;
[meetEntity.managedObjectContext save:&mySavingError];
if (mySavingError) NSLog(#"In %# and mySavingError is %#",NSStringFromClass([self class]), mySavingError);
}
}
return results;
}
Where whichPhoto is the title of the link between the two Core Data Entities.
Here is NSLog Statement:
2014-08-13 14:40:45.334 ITrackXC[12054:60b] thisMeetsPhoto should equal nil and equals (null)
2014-08-13 14:41:37.095 ITrackXC[12054:60b] In MeetPhotoViewController and executing imagePickerController:didFinishPickingImage:editingInfo:
2014-08-13 14:41:37.583 ITrackXC[12054:60b] In MeetPhoto and matches = 1
2014-08-13 14:41:37.589 ITrackXC[12054:60b] whichMeetPhotographed = <MarksFromMeets: 0x1700c5be0> (entity: MarksFromMeets; id: 0xd000000000300004 <x-coredata://ED56838C-9F27-451D-97CA-01AF0FC38830/MarksFromMeets/p12> ; data: {
athleteGrade = "12th Grade";
event = "5000 Meters";
eventPR = 1;
eventSB = 1;
markInEvent = "19:03";
meetDate = "2013-11-02 07:00:00 +0000";
meetID = 78103;
meetName = "OSAA 3A/2A/1A State Championships";
photoThumbNail = "<UIImage: 0x170281b80>";
placeInEvent = 2;
raceSorter = 5000;
seasonName = 2013;
sortMark = 1143;
standardOrMetric = nil;
uniqueResultID = 10032696;
whichPhoto = "0x178236d80 <x-coredata:///MeetPhoto/t9C5E481D-5911-47C9-AA8B-6015AAD1C23C2>";
whoRan = "0xd000000000080000 <x-coredata://ED56838C-9F27-451D-97CA-01AF0FC38830/AthleteInfo/p2>";
})
photo = <UIImage: 0x17009b440>
thumbnail = <UIImage: 0x170281b80>
2014-08-13 14:41:37.599 ITrackXC[12054:60b] NSManagedObjects did change.
2014-08-13 14:41:39.444 ITrackXC[12054:60b] NSManagedContext did save.
I do not get any errors. However when I look at the TableView where the data is displayed, the photos are still part of the record.
I can get rid of the thumbnail and associated photo by setting them to "nil". Is there any problem with this approach?
Setting attribute values to nil is how you're supposed to do this, so no, there's no problem with it. The deleteObject: method is only for when you want to delete a managed object. Using it in other cases might not crash, but it also won't have the effect you're aiming for.
In the case of the photo, you might need to delete an object, but it's hard to tell from your code. You seem to want to get rid of meetEntity.whichPhoto.photo. I don't know what whichPhoto is; if it's a managed object, you might want to call deleteObject on myEntity.whichPhoto to get rid of it. If nobody else is using it, that is.

Storing CLLocation (latitude, longtitude data) in to Core Data

i want to ask a question about core location and core data. i looked some questions but couldnt do that..
i have a application which stores some textfields, photos, date and time datas in UITableView With core data, i stored everything (photos, texts, date etc.) Now trying to store Location data i couldnt do.
this is some of my code here.
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
NSDateFormatter *myFormatter = [[NSDateFormatter alloc] init];
[myFormatter setDateFormat:#"MM-dd-yyyy HH:mm"];
[myFormatter setTimeZone:[NSTimeZone systemTimeZone]];
todaysDate = [myFormatter stringFromDate:[NSDate date]];
myDateLabel.text = todaysDate;
UIView *patternBg = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
patternBg.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background01.png"]];
self.tableView.backgroundView = patternBg;
// If we are editing an existing picture, then put the details from Core Data into the text fields for displaying
if (currentPicture)
{
[companyNameField setText:[currentPicture companyName]];
[myDateLabel setText:[currentPicture currentDate]];
if ([currentPicture photo])
[imageField setImage:[UIImage imageWithData:[currentPicture photo]]];
}
}
in the saveButton
- (IBAction)editSaveButtonPressed:(id)sender
{
// For both new and existing pictures, fill in the details from the form
[self.currentPicture setCompanyName:[companyNameField text]];
[self.currentPicture setCurrentDate:[myDateLabel text]];
[self.currentPicture setCurrentTime:[myTimeLabel text]];
[self.currentPicture setLatitudeData:[_latitudeLabel text]];
[self.currentPicture setLongtidueData:[_longtitudeLabel text]];
}
and last one, my locationManager's method..
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
_longtitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
_latitudeLabel.text = [NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
[self->locationManager stopUpdatingLocation];
}
}
i tried "[locationmanager stopUpdatingLocation];" many times, but when i entered the app, code starts to calculating latitude and longtitude data, i just want to take that data 1 time, and store..
Thanks!
If calling stopUpdatingLocation doesn't stop location updates, then most likely self->locationManager is nil. That would mean you're not really making the call.
It's hard to be sure exactly why this would happen, except that your code seem to make a point of not using any semantics implied by a #property declaration. Just assigning to location in viewDidLoad avoids any declaration, and looking up the manager using self->locationManager does as well. Assuming that location is a property, you should assign it to self.locationManager, and use that when looking it up as well.
A couple things:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
if (locationAge > 5) return; // ignore cached location, we want current loc
if (newLocation.horizontalAccuracy <= 0) return; // ignore invalid
// wait for GPS accuracy (will be < 400)
if (newLocation.horizontalAccuracy < 400) {
_longtitudeLabel.text = [NSString stringWithFormat:#"%.8f", newLocation.coordinate.longitude];
_latitudeLabel.text = [NSString stringWithFormat:#"%.8f", newLocation.coordinate.latitude];
[manager stopUpdatingLocation];
}
}
In your didUpdateToLocation do this code
(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
if (locationAge > 5) return;
// ignore cached location, we want current loc
if (newLocation.horizontalAccuracy <= 0) return; // ignore invalid
// wait for GPS accuracy (will be < 400)
if (newLocation.horizontalAccuracy < 400) {
_longtitudeLabel.text = [NSString stringWithFormat:#"%.8f", newLocation.coordinate.longitude];
_latitudeLabel.text = [NSString stringWithFormat:#"%.8f", newLocation.coordinate.latitude];
[manager stopUpdatingLocation];
//assign nil to locationManager object and delegate
locationManager.delegate = nil;
locationManager = nil;
}
}
Thanks.

Selecting TableView cell returns incorrect object

I followed a tutorial I found online to create a tableview with sections and an index from an array of custom objects. This code works with the exception that when I select a row in the table I the index path for that section and not for the entire array. I can see why it doesn't work but I can't figure out how to address the fix, this is my cell for tableview code.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"NameCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure the cell...
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
int displayOrder = [defaults integerForKey:#"displayOrder"];
int sortOrder = [defaults integerForKey:#"sortOrder"];
NSString *alphabet = [listIndex objectAtIndex:[indexPath section]];
NSPredicate *sectionPredicate = [[NSPredicate alloc] init];
if (sortOrder == 1) {
//NSLog(#"fName is predicate at cell level");
sectionPredicate = [NSPredicate predicateWithFormat:#"fName beginswith[c] %#", alphabet];
} else {
//NSLog(#"lName is predicate at cell level");
sectionPredicate = [NSPredicate predicateWithFormat:#"lName beginswith[c] %#", alphabet];
}
NSArray *sectionContacts = [filteredList filteredArrayUsingPredicate:sectionPredicate];
if (isSearching) {
current = [filteredList objectAtIndex:indexPath.row];
} else{
current = [sectionContacts objectAtIndex:indexPath.row];
}
if (displayOrder == 1) {
NSString *fullName = [NSString stringWithFormat:#"%# %#",[current valueForKey:#"fName"],[current valueForKey:#"lName"]];
[cell.textLabel setText:fullName];
//NSLog(#"FirstNameFirst");
} else {
NSString *fullName = [NSString stringWithFormat:#"%# %#",[current valueForKey:#"lName"],[current valueForKey:#"fName"]];
[cell.textLabel setText:fullName];
//NSLog(#"LastNameFirst");
}
[cell.detailTextLabel setText:[current valueForKey:#"extension"]];
return cell; }
THen I call the segue with this code.
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:#"showContact"]) {
DetailViewController *dvc = [segue destinationViewController];
NSIndexPath *path = [self.tableView indexPathForSelectedRow];
NSDictionary *c = [filteredList objectAtIndex:path.row];
[dvc setCurrentContact:c];
[searchBar resignFirstResponder];
} }
The problem is that the objectAtIndex:path.row returns the index for that section but it isn't modified for the entire array, so if a name in the "B" section that is at index 4 of that section is tapped it returns the object at index 4 of the primary array. I have been scratching my head to figure out how to get the index for the full array and not for the one that is only local to that section.
I'll buy you a 6 pack of your favorite beverage if you can help!
Thanks!
You do it the same way that they do it in the first function, so change your prepareForSegue to this:
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"showContact"]) {
DetailViewController *dvc = [segue destinationViewController];
NSIndexPath *path = [self.tableView indexPathForSelectedRow];
NSDictionary *c;
NSString *alphabet = [listIndex objectAtIndex:[path section]];
NSPredicate *sectionPredicate = [[NSPredicate alloc] init];
if (sortOrder == 1) {
sectionPredicate = [NSPredicate predicateWithFormat:#"fName beginswith[c] %#", alphabet];
} else {
sectionPredicate = [NSPredicate predicateWithFormat:#"lName beginswith[c] %#", alphabet];
}
NSArray *sectionContacts = [filteredList filteredArrayUsingPredicate:sectionPredicate];
if (isSearching) {
c = [filteredList objectAtIndex:path.row];
} else{
c = [sectionContacts objectAtIndex:path.row];
}
[dvc setCurrentContact:c];
[searchBar resignFirstResponder];
}
}
Note that it would probably be best to pull the common code out and make a separate function instead of using it twice like this.

Find assets in library - add to a AVMutableComposition - export = crash

I've been struggling with adding assets from the iPhone Photo Library to a AVMutableComposition and then export them. Here is what I got:
Finding the assets: (here I grab the AVURLAsset)
-(void) findAssets {
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
// Enumerate just the photos and videos group by using ALAssetsGroupSavedPhotos.
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
// Within the group enumeration block, filter to enumerate just videos.
[group setAssetsFilter:[ALAssetsFilter allVideos]];
[group enumerateAssetsUsingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop){
// The end of the enumeration is signaled by asset == nil.
if (alAsset) {
ALAssetRepresentation *representation = [alAsset defaultRepresentation];
NSURL *url = [representation url];
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];
// Do something interesting with the AV asset.
[thumbs addObject:alAsset];
[assets addObject:avAsset];
}else if(alAsset == nil){
[self createScroll];
}
}];
}
failureBlock: ^(NSError *error) {
// Typically you should handle an error more gracefully than this.
NSLog(#"No groups");
}];
[library release];
}
Here I add a asset to my composition (I use the first object in the array for testing only.
-(void) addToCompositionWithAsset:(AVURLAsset*)_asset{
NSError *editError = nil;
composition = [AVMutableComposition composition];
AVURLAsset* sourceAsset = [assets objectAtIndex:0];
Float64 inSeconds = 1.0;
Float64 outSeconds = 2.0;
// calculate time
CMTime inTime = CMTimeMakeWithSeconds(inSeconds, 600);
CMTime outTime = CMTimeMakeWithSeconds(outSeconds, 600);
CMTime duration = CMTimeSubtract(outTime, inTime);
CMTimeRange editRange = CMTimeRangeMake(inTime, duration);
[composition insertTimeRange:editRange ofAsset:sourceAsset atTime:composition.duration error:&editError];
if (!editError) {
CMTimeGetSeconds (composition.duration);
}
}
And finally I export the comp and here it crashes
-(void)exportComposition {
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetPassthrough];
NSLog (#"can export: %#", exportSession.supportedFileTypes);
NSArray *dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [dirs objectAtIndex:0];
NSString *exportPath = [documentsDirectoryPath stringByAppendingPathComponent:EXPORT_NAME];
[[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
NSURL *exportURL = [NSURL fileURLWithPath:exportPath];
exportSession.outputURL = exportURL;
exportSession.outputFileType = AVFileTypeQuickTimeMovie;//#"com.apple.quicktime-movie";
[exportSession exportAsynchronouslyWithCompletionHandler:^{
NSLog (#"i is in your block, exportin. status is %d",
exportSession.status);
switch (exportSession.status) {
case AVAssetExportSessionStatusFailed:
case AVAssetExportSessionStatusCompleted: {
[self performSelectorOnMainThread:#selector (exportDone:)
withObject:nil
waitUntilDone:NO];
break;
}
};
}];
}
Does anyone have an idea of what it might be? It crashes on
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetPassthrough];
And I tried different presets and outputFileTypes.
Thanks
* SOLVED *
I have to answer my own question now when I have solved. It's amazing that I've been struggling with this for a whole day and then I fix it right after posting a question :)
I changed and moved:
composition = [AVMutableComposition
composition];
to:
composition = [[AVMutableComposition
alloc] init];
I think I was too tired when I was working on this yesterday. Thanks guys!

Is it possible to open addContactScreen from native app?

I want to replicate add contact like screen iPhone has. But I don't want to add contact in default phonebook instead I want to use the details in my app. Is it possible to open default add new contact screen and get all the data? If yes then how? A simple code snippet will be very helpful. Here is an image of add contact screen to better understand my question
You can try to add the contact to the address book, pull the data and then delete it from the address book. this is a fairly simple process.
I use this function to save all the person data to core data in my app. and then to delete the person from the addressBook.
+(void)savePersonDetails:(Person*)person{
ABAddressBookRef addressBook = ABAddressBookCreate();
ABRecordRef ref = ABAddressBookGetPersonWithRecordID(addressBook,[person.ID intValue]);
ABMutableMultiValueRef multiPhones = ABRecordCopyValue(ref, kABPersonPhoneProperty);
for (CFIndex i = 0; i < ABMultiValueGetCount(multiPhones); i++) {
NSString *phoneNumber = (NSString*)ABMultiValueCopyValueAtIndex(multiPhones, i);
CFStringRef locLabel = ABMultiValueCopyLabelAtIndex(multiPhones, i);
NSString *phoneNumberLabel =(NSString*) ABAddressBookCopyLocalizedLabel(locLabel);
CFRelease(locLabel);
Phone *phone =(Phone*)[NSEntityDescription insertNewObjectForEntityForName:#"Phone" inManagedObjectContext:person.managedObjectContext];
phone.number = phoneNumber;
phone.label = phoneNumberLabel;
phone.person = person;
[person addPhonesObject:phone];
[person release];
CFRelease(phoneNumber);
CFRelease(phoneNumberLabel);
}
CFRelease(multiPhones);
ABMutableMultiValueRef multiEmail = ABRecordCopyValue(ref, kABPersonEmailProperty);
for (CFIndex i = 0; i < ABMultiValueGetCount(multiEmail); i++) {
NSString *mail = (NSString*)ABMultiValueCopyValueAtIndex(multiEmail, i);
CFStringRef locLabel = ABMultiValueCopyLabelAtIndex(multiEmail, i);
NSString *mailLabel =(NSString*) ABAddressBookCopyLocalizedLabel(locLabel);
Mail *mailEntity =(Mail*)[NSEntityDescription insertNewObjectForEntityForName:#"Mail" inManagedObjectContext:person.managedObjectContext];
mailEntity.mail = mail;
mailEntity.label = mailLabel;
mailEntity.person = person;
[person addMailsObject:mailEntity];
CFRelease(locLabel);
[mail release];
[mailLabel release];
}
CFRelease(multiEmail);
ABMultiValueRef streets = ABRecordCopyValue(ref, kABPersonAddressProperty);
for (CFIndex j = 0; j<ABMultiValueGetCount(streets);j++){
CFDictionaryRef dict = ABMultiValueCopyValueAtIndex(streets, j);
CFStringRef typeTmp = ABMultiValueCopyLabelAtIndex(streets, j);
CFStringRef lbl = ABAddressBookCopyLocalizedLabel(typeTmp);
NSString *street = [(NSString *)CFDictionaryGetValue(dict, kABPersonAddressStreetKey) copy];
NSString *city = [(NSString *)CFDictionaryGetValue(dict, kABPersonAddressCityKey) copy];
NSString *state = [(NSString *)CFDictionaryGetValue(dict, kABPersonAddressStateKey) copy];
NSString *zip = [(NSString *)CFDictionaryGetValue(dict, kABPersonAddressZIPKey) copy];
NSString *country = [(NSString *)CFDictionaryGetValue(dict, kABPersonAddressCountryKey) copy];
Address *addressEntity =(Address*)[NSEntityDescription insertNewObjectForEntityForName:#"Address" inManagedObjectContext:person.managedObjectContext];
addressEntity.label = (NSString*)lbl;
addressEntity.street = street;
addressEntity.city = city;
addressEntity.state = state;
addressEntity.zip = zip;
addressEntity.country = country;
[street release];
[city release];
[state release];
[zip release];
[country release];
CFRelease(dict);
CFRelease(lbl);
CFRelease(typeTmp);
addressEntity.person = person;
[person addAddressesObject:addressEntity];
}
CFRelease(streets);
ABMutableMultiValueRef multiURL = ABRecordCopyValue(ref, kABPersonURLProperty);
for (CFIndex i = 0; i < ABMultiValueGetCount(multiURL); i++) {
NSString *url = (NSString*)ABMultiValueCopyValueAtIndex(multiURL, i);
CFStringRef locLabel = ABMultiValueCopyLabelAtIndex(multiPhones, i);
NSString *urlLabel =(NSString*) ABAddressBookCopyLocalizedLabel(locLabel);
Url *urlEntity =(Url*)[NSEntityDescription insertNewObjectForEntityForName:#"Url" inManagedObjectContext:person.managedObjectContext];
urlEntity.url = url;
urlEntity.label = urlLabel;
urlEntity.person = person;
[person addUrlsObject:urlEntity];
CFRelease(locLabel);
[urlLabel release];
[url release];
}
CFRelease(multiURL);
ABAddressBookRemoveRecord(addressBook, ref, nil);
ABAddressBookSave(addressBook, nil);
CFRelease(addressBook);
if (![person.managedObjectContext save:&error]) {
// Update to handle the error appropriately.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1); // Fail
}
}

Resources