Store array of ABRecordRef - iphone-sdk-4.1

How can we store and access a list of ABRecordRef so that we can use this in another class and later on?

You can get recordId from the record of type ABRecordRef from
addressBook Then convert it into NSString. Store it in NSUserDefaults
When you want to fetch the record...
fetch that recordId from NSUserDefaults,Convert it in integer
then use
ABRecordRef myRecord =
ABAddressBookGetPersonWithRecordID(addressBook, recordId);
So you will get the record which you saved earlier.

Try This:
ABAddressBookRef addressBook = ABAddressBookCreate();
ABRecordRef person = ABRecordGetRecordID(1); // Or whatever you're using to get the record.
// do this for each piece of information you need:
NSString *firstName = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
NSString *lastName = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
// Get your receiving dict ready:
NSMutableDictionary *personDict = [NSMutableDictionary dictionary];
// then test them for a value (don't want nil values in the dictionary)
// Add each value as you test it.
if (firstName) {
[personDict setObject:firstName forKey:#"FistName"];
}
if (lastName) {
[personDict setObject:lastName forKey:#"LastName"];
}
// Add the personDict to NSUserDefaults:
[[NSUserDefaults standardDefaults] setObject:personDict forKey:#"MyPersonsDictionary"];
// Clean up after yourself:
[firstName release];
[lastNmae release];
That should be it.

Related

Unable to add object to NSMutableArray with TFHpple

I tried to add object to my mutable array using TFHlle parse html in this code but it return null for object in my array, but in the for loop, I log the result of '[element objectForKey:#"title"]' and it returns result I want.
How I can add the result of element [objectForKey:#"title"] to my array?
TFHpple *htmlParseResult = [TFHpple hppleWithHTMLData:self.responseData];
NSString *coursesXpathQueryString = #"//h2[#class='main']/a";
NSArray *coursesNodes = [htmlParseResult searchWithXPathQuery:coursesXpathQueryString];
NSMutableArray *fitCourse = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in coursesNodes) {
[fitCourse addObject:[element objectForKey:#"title"]];
}
I think
NSArray *coursesNodes = [htmlParseResult searchWithXPathQuery:coursesXpathQueryString];
should be change to:
NSArray *coursesNodes = [NSArray arrayWithArray:[htmlParseResult searchWithXPathQuery:coursesXpathQueryString]];
I am not sure this works but you can try.

get all attributes for entity from core data

how does my fetchedResultsController method look like, if I want to fetch all my attributes for an entity from core data? I only know and understand how to fetch data for a tableView and I think that is where all my confusion is coming from.
Here is my Core-Data setup:
I'm trying to fill an array with all the Attributes my Setting entity has and the show those values via NSLog output in my debug console.
Here is what I changed so far:
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *newEntry = [NSEntityDescription insertNewObjectForEntityForName:#"Setting" inManagedObjectContext:context];
//NSManagedObject *newSetting = [NSEntityDescription insertNewObjectForEntityForName:#"Setting" inManagedObjectContext:context];
[newEntry setValue: #"StudiSoft" forKey:#"settingName"];
if (_overrideSysTimeSwitch.on) {
[newEntry setValue: #YES forKey:#"settingSysTimeOverride"];
//editSetting.settingSysTimeOverride = #YES;
NSLog(#"IF A");
} else {
//[newEntry setValue: #NO forKey:#"settingSysTimeOverride"];
//editSetting.settingSysTimeOverride = #NO;
NSLog(#"IF B");
}
if (_timeFormatSwitch.on) {
//[newEntry setValue: #YES forKey:#"settingTimeFormat"];
//editSetting.settingTimeFormat = #YES;
NSLog(#"IF C");
} else {
//[newEntry setValue: #NO forKey:#"settingTimeFormat"];
//editSetting.settingTimeFormat = #NO;
NSLog(#"IF D");
}
[self.settingsArray addObject:#"StudiSoft"];
NSError *error;
[context save:&error];
I'm using this code-snipped that and I'm able to modify the core data content.
However, every time I run this code, it of course adds a new object.
I've been looking for a way to update existing Attributes in my Entity, or modify them, but I could NOT find them.
Anyhow this is a good step into the right direction.
I created a completely new project, with just one view, once I have it working on the main view I'm going to experiment with segues....
But for now, how would I update or change existing attributes?
Thanks guys!!
This is my editSave Method to store some data in core data:
- (IBAction)editSave:(UIBarButtonItem *)sender
{
if ([_editSaveButton.title isEqualToString:#"Edit"])
{
[self setTitle:#"Edit Settings"];
//self.title = #"Edit Settings";
_overrideSysTimeSwitch.userInteractionEnabled = YES;
_timeFormatSwitch.userInteractionEnabled = YES;
_editSaveButton.title = #"Save";
} else if ([_editSaveButton.title isEqualToString:#"Save"])
{
[self setTitle:#"Settings"];
//self.title = #"Settings";
_overrideSysTimeSwitch.userInteractionEnabled = NO;
_timeFormatSwitch.userInteractionEnabled = NO;
_editSaveButton.title = #"Edit";
// #############################################################
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
//NSManagedObject *newEntry = [NSEntityDescription insertNewObjectForEntityForName:#"Setting" inManagedObjectContext:context];
//[newEntry setValue: #"StudiSoft" forKey:#"settingName"];
/*NSString *firstName = [anEmployee firstName];
Employee *manager = anEmployee.manager;
Setting *newSetting = [NSString #"Test"];
[newSetting setValue:#"Stig" forKey:#"settingName"];
[aDepartment setValue:[NSNumber numberWithInteger:100000] forKeyPath:#"manager.salary"];*/
//editSetting.settingName = #"Test";
if (_overrideSysTimeSwitch.on) {
//[newEntry setValue: #YES forKey:#"settingSysTimeOverride"];
editSetting.settingSysTimeOverride = #YES;
NSLog(#"IF A");
} else {
//[newEntry setValue: #NO forKey:#"settingSysTimeOverride"];
editSetting.settingSysTimeOverride = #NO;
NSLog(#"IF B");
}
if (_timeFormatSwitch.on) {
//[newEntry setValue: #YES forKey:#"settingTimeFormat"];
editSetting.settingTimeFormat = #YES;
NSLog(#"IF C");
} else {
//[newEntry setValue: #NO forKey:#"settingTimeFormat"];
editSetting.settingTimeFormat = #NO;
NSLog(#"IF D");
}
//[self.settingsArray addObject:#"StudiSoft"];
NSError *error = nil;
//if ([self.managedObjectContext hasChanges]) {
//NSLog(#"SAVE & DISMISS conetx has changed");
if (![context save:&error]) { // save failed
NSLog(#"Save failed: %#", [error localizedDescription]);
} else { // save succeeded
NSLog(#"Save Succeeded");
}
//}
//[self.tableView reloadData];
// #############################################################
}
}
Debug Output:
2014-06-10 19:09:29.881 SettingsCoreData[508:60b] Entry #5: <Setting: 0x8f983e0> (entity: Setting; id: 0x8f97030 <x-coredata://FA78AB86-3225-4B1E-97DD-3F31F5323A18/Setting/p6> ; data: {
settingName = StudiSoft;
settingSysTimeOverride = 0;
settingTimeFormat = 0;
})
2014-06-10 19:09:29.883 SettingsCoreData[508:60b] Entry #6: <Setting: 0x8f98430> (entity: Setting; id: 0x8f97040 <x-coredata://FA78AB86-3225-4B1E-97DD-3F31F5323A18/Setting/p7> ; data: {
settingName = StudiSoft;
settingSysTimeOverride = 1;
settingTimeFormat = 1;
})
Now I should be able to use something like this in my viewDidLoad, right?
if (editSetting.settingSysTimeOverride.boolValue == 0) {
_overrideSysTimeSwitch.on = NO;
} else {
_overrideSysTimeSwitch.on = YES;
}
But it doesn't work as I thought it will :-(
Next you need to call -performFetch: on the NSFetchedResultsController. Make sure you check the response and handle the error if the response is NO.
From there your NSFetchedResultsController is populated and ready to be used. You can then grab individual elements via -objectAtIndex: or you can grab them all with -fetchedObjects.
I would suggest just reviewing the documentation on the methods that are available as it has pretty strong and clear documentation.
Update
If you are not receiving any data then break it down. Take the NSFetchRequest that you created and call -executeFetchRequest:error: against your NSManagedObjectContext and see if you get any data back.
If you do then there is something wrong with your handling of the NSFetchedResultsController.
If you don't then there is something wrong with your NSFetchRequest or you don't have any data in your store.
Update
Sounds like you need to read a book on how Core Data works.
A NSFetchRequest is a query against Core Data so that objects can be returned from the store. You can pass a NSFetchRequest to a NSFetchedResultsController so that the NSFetchedResultsController can monitor the store for changes and let your view controller know when those changes occur.
A NSFetchRequest can also be executed directly against the NSManagedObjectContext and you can retrieve the results directly. You do that by calling -executeFetchRequest:error: against your NSManagedObjectContext and getting a NSArray back. You can then check that NSArray to see if you get any results.
If you do not understand that paragraph then you need to take a step back and read the tutorials on Core Data and/or read a book on Core Data. I can recommend an excellent book on the subject ;-)

Export CoreData objects into NSDictionary or NS Array

I have a Core Data Object Which is Composed of Different Types NSString, Float,NSDATA,....
<Shoplog: 0x9c78d20> (entity: Shoplog; id: 0x9c77050 <x-coredata://828289C5-E1B8-48A6-B2A0-F68B7DF21F2E/Shoplog/p5> ; data: {
categoryname = Ines;
comments = nil;
date = nil;
email = "iloveyou#gmail.com";
image = <ffd8ffe0 00104a46 49460001 01000001 00010000 ffe10058 45786966 00004d4d 002a0000 00080002 01120003 00000001 0001>;
phone = 800;
price = 9988;
shop = "";
websiteurl = "http://www.google.com";
})
The issue is i want to Export this NSManaged Object into an NSArray or NSDictionary in order to write it to a file , in order to send it by mail to another User , & Open it from His App.
So Whenever i am Trying to use this Code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Shoplog.slog"];
[savedData writeToFile:filePath atomically:YES];
It Gives me a very small File 135bytes no matter how big is the Selected NSManagedObject i get the same Size .
i need help to understand what is going on wrong ?
I think about 1 Solutions :
1- Transfer the NsManagedObject to NSMutableArray using KVC Method
Although i still Believe there is a smarter Solution for this Problem , so if someone can help i will be Grateful.
Thank you
I have my Answer in the Following Link , It is Very Easy to Implement, Just follow the Steps
Serializing (Archiving/Unarchiving) an NSManagedObject Graph

Core Data NSMutable Set trouble

Ok I am trying to grab a NSMutable Set. Yes I have a previous post on this but this is slightly different. I have A player entity and a team entity. It is set up as a one to many relationship... On a different view controller I added players to the team. Now I am trying to get that teams players to show up on a table view... I am fetching the information as follows.
- (NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSString *entityName = #"Team";
NSLog(#"Setting up a Fetched Results Controller for the Entity named %#", entityName);
// 2 - Request that Entity
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
_managedObjectContext = delegate.managedObjectContext;
// 4 - Sort it
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"players"
ascending:NO
selector:#selector(localizedCaseInsensitiveCompare:)]];
// 5 - Fetch it
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
Then on my cell for row at index path I am setting the Player object to the fetched results as follows
Player *p = [_fetchedResultsController objectAtIndexPath:indexPath];
Then, I am setting the title of the cell like so.
cell.textLabel = p.firstName;
I am getting the error
reason: 'to-many key not allowed her
I am wondering what am I doing wrong???
Figured it out! I was sorting on a one to many relationship which is a NO NO in Core Data. I switched to sort on the player object and added a predicate to find the proper players I needed.

UISwitch core data

UITextField *textField;
UISwitch *someSwitch;
NSManagedObject *editedObject;
NSString *editedFieldKey;
NSString *editedFieldName;
NSString *z=[NSString stringWithFormat:#"%#",[editedObject valueForKey:editedFieldKey]];
NSString *y=[NSString stringWithFormat:#"b"];
if(z==y){
[someSwitch setOn:YES animated:YES];
}
else{[someSwitch setOn:NO animated:YES];}
-(IBAction) toggleButtonPressed{
NSString *a=[NSString stringWithFormat:#"a"];
NSString *b=[NSString stringWithFormat:#"b"];
if(someSwitch.on){
[editedObject setValue:b forKey:editedFieldKey];
}
else{
[editedObject setValue:a forKey:editedFieldKey];
}
}
-(IBAction)save {
NSUndoManager * undoManager = [[editedObject managedObjectContext] undoManager];
[undoManager setActionName:[NSString stringWithFormat:#"%#", editedFieldName]];
if (editingName){
[editedObject setValue:textField.text forKey:editedFieldKey];
}else{
[self toggleButtonPressed];
}
[self.navigationController popViewControllerAnimated:YES];
}
I can't get a UISwitch to work in the context of Core Data and detail view controllers. When you create a BOOL in core data, then have the corresponding class made in xcode, it makes an NSNumber. This is fine but instead of making "0" and "1"'s when data is saved and recalled, it comes up with very large integers (7-8 digits). What I did above was to store the information as a binary string, using "a" or "b" for the string for storage. This hasn't worked well, mostly because I can't get the UISwitch to load with the previously stored value (on or off). I am sure this has been dealt with before, but I can't find much documentation online. If there are any ideas or suggestions, relative to the above code, let me know. Thanks.
2011-12-06 15:49:41.042 sampNav[820:207] 101783056
2011-12-06 15:49:41.043 sampNav[820:207] 80887600
- (IBAction)save {
NSUndoManager * undoManager = [[editedObject managedObjectContext] undoManager];
[undoManager setActionName:[NSString stringWithFormat:#"%#", editedFieldName]];
if (editingName){
[editedObject setValue:textField.text forKey:editedFieldKey];
}else{
[self toggleButtonPressed];
}
[self.navigationController popViewControllerAnimated:YES];
}
-(IBAction) toggleButtonPressed{
if (someSwitch.on==YES)
{
[editedObject setValue:[NSNumber numberWithInt:1] forKey:editedFieldKey];
NSLog(#"%d",[editedObject valueForKey:editedFieldKey]);
}
else [editedObject setValue:[NSNumber numberWithInt:0] forKey:editedFieldKey];
NSLog(#"%d",[editedObject valueForKey:editedFieldKey]);
}
The problem is when these values are stored as NSNumber objects the values are large integers. The NSLog is given at the very top. Can anyone explain this?
your code as it stands:
if(z==y){
Is comparing pointers not the strings, you need:
if([z isEqualToString:y]){
To get the string comparison to work so that the switch has the correct initial state...
But you really want to use the core data BOOL version and get the value of the NSNumber that is stored in the NSManagedObject. I suspect you are not converting the NSNumber pointer to object into a boolValue.
if([[editedObject valueForKey:editedFieldKey] boolValue]) {

Resources