Iterating over a NSDictionary to add values to an object - ios

I am trying to iterate through a NSDictionary and add all the values in that dictionary to an object. So i added new cocoa class file to my project and subclassed it with NSObject. (named it customClass)
In my custom class.h:
- (void)printDir; // iterate through the direcory and print it.
#property (nonatomic, retain) NSMutableDictionary *objDictionary;
In customClass.m the defination of printDir method is as:
- (void)printDir {
_objDictionary = [[NSMutableDictionary alloc ]init];
for(id key in _objDictionary) {
id value = [_objDictionary objectForKey:key];
NSLog(#"Values in Objects Dictionary");
NSLog(#"%#",value);
}
}
In my ViewController.m i am trying to iterate through a NSDirectory and add all the values of that directory to the NSMutableDictionary of the object. For which,
for(id key in jsonDictionary.allKeys) {
id value = [jsonDictionary objectForKey:key];
[obj.objDictionary setObject:value forKey:key];
}
When i run the project the printDir method of the object get called, however the for loop does not execute. Can someone point out where i am going wrong. Thanks.

_objDictionary = [[NSMutableDictionary alloc ]init];
Change this line in your printDir method to init method of your custom class. The problem now is each time when you reach your printDir method, it is re-assigning the _objDictionary to nil. So the loop will not execute

In printDir Function you are allocating a dictionary objDictionary again.... so it over right your actual value supplies by your view controller .... You just change your function to this
In .h file
- (void)printDirwithDictionary :(NSMutableDictionary *)dict;
And in .m file
- (void)printDirwithDictionary:(NSMutableDictionary *)dict {
_objDictionary = [[NSMutableDictionary alloc] initWithDictionary:dict]
for(id key in _objDictionary) {
id value = [_objDictionary objectForKey:key];
NSLog(#"Values in Objects Dictionary");
NSLog(#"%#",value);
}
}
In ViewController.m Follow This code
NSMutableDictionary *dictToPass = [[NSMutableDictionary alloc]init];
for(id key in jsonDictionary.allKeys) {
id value = [jsonDictionary objectForKey:key];
[dictToPass setObject:value forKey:key];
}
[obj printDirWithDictionary:dictToPass];
And Call from View Controller will be like this
And Then Follow the sameprocedure . Hope This will Work Properly .

Related

Objective C - How To Keep Reference To Multiple Objects With Keys Just Like How NSMutableDictionary Works

I just learned how to make use of KVO, but only the basics. What I need to achieve is something like this:
I have a delegate call that passes a Speaker object.
- (void)onSpeakerFound:(Speaker *)speaker
Once I receive this Speaker in the UI part, from there I will assign observers for this object.
But, this is just for one speaker. What if I have multiple speakers to keep track of. I need to assign observers separately for those speakers and then at the same time I wish to keep their references for further updates to the values.
Each speaker could be updated from time to time. So when I notice that there is a change that happened on a speaker, I wish to access the reference to that speaker and update the values just like how NSMutableDictionary works.
NSMutableDictionary makes a copy of an object set to it so it will be a difference object if I get it again from the dictionary.
So, is there a class that allows me to keep track of an object by just keeping a reference only to that object without making a copy of it?
EDIT: A Test Made To Verify That When An Instantiated Object is Set in an NSMutableDictionary, The Instantiated Object is not referenced with the one set inside NSMutableDictionary.
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
NSString *obj = #"initial value";
NSString *key = #"key";
[dict setObject:obj forKey:key];
NSLog(#"Object is now %#", [dict objectForKey:key]);
obj = #"changed value";
NSLog(#"Object is now %#", [dict objectForKey:key]);
}
Log:
2016-07-26 21:04:58.759 AutoLayoutTest[49723:2144268] Object is now initial value
2016-07-26 21:04:58.761 AutoLayoutTest[49723:2144268] Object is now initial value
NSMutableDictionary makes a copy of an object set to it...
That is not correct; it will add a reference to the object. It will be the same object referenced inside and outside the Objective-C collection.
So, is there a class that allows me to keep track of an object...?
Probably NSMutableSet if you just want a list of the objects. That will take care that you have a unique reference to each object, however you need to implement the methods hash and isEqual on those objects so they behave correctly. Otherwise NSMutableDictionary if you want fast look-up by key.
-try this one
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
NSString *obj = #"initial value";
NSString *key = #"key";
[dict setObject:obj forKey:key];
NSLog(#"Object is now %#", [dict objectForKey:key]);
obj = #"changed value";
[dict setObject:obj forKey:Key];
NSLog(#"Object is now %#", [dict objectForKey:key]);
}

Combining dictionaries: No class method for selector "addEntriesFromDictionary"

I am struggling with a dictionary in which I want to create a new dictionary from a series of keys (P, SP, and RP).
I have attempted to create a new NSMutableDictionary that combines individual Dictionaries that have have all the values for the P, SP, and RP keys respectively, but have gotten the error "No class method for selector "addEntriesFromDictionary" "
Here is my code:
NSMutableDictionary *newDict = [NSMutableDictionary addEntriesFromDictionary:self.allSPPositions];
and
#interface className ()
- (void)addEntriesFromDictionary:(NSDictionary *)otherDictionary;
#end
#implementation className
- (void)viewDidLoad {
Any help or insight would be appreciated! Thanks!
The compiler is telling you exactly what's wrong. You're trying to add items from a dictionary to the NSMutableDictionary class. You need to send the ad items from dictionary message to an instance of NSMutableDictionary.
This line:
NSMutableDictionary *newDict =
[NSMutableDictionary addEntriesFromDictionary:self.allSPPositions];
Should read
NSMutableDictionary *newDict =
[someDictionary addEntriesFromDictionary: self.allSPPositions];
(Where someDictionary is the dictionary to which you want to add items.)
or even
NSUInteger count = [self.allSPPositions count];
NSMutableDictionary *newDict =
[NSMutableDictionary dictonaryWithCapacity: count];
[newDict addEntriesFromDictionary: self.allSPPositions];
(Since your code appears to be trying to create a new, mutable dictionary and add the contents of self.allSPPositions.)
If your goal is to get a mutable copy of self.allSPPositions, there is a cleaner way to do that:
NSMutableDictionary *mutablePositions = [self.allSPPositions mutableCopy];
Uhh, here's an example that will compile and use the method in question, you should probably NOT call that method in your Interface since it's part of Apple's framework and is already predefined, unless you have a special reason for doing so:
NSMutableDictionary *dict =[[NSMutableDictionary alloc] init];
[dict setValue:#"Seattle" forKey:#"name"];
[dict setObject:[NSNumber numberWithInt:3] forKey:#"age"];
[dict setObject:[NSDate date] forKey:#"date"];
dict[#"city"]=#"Seattle";
[dict addEntriesFromDictionary:[NSMutableDictionary dictionaryWithObjectsAndKeys: #"Washington",#"location", nil]];
This is merely meant to get you started, but it shows you how to do this so that it works for you in your circumstances

Append NSStrings and NSNumber to NSMutableArrays and make NSMutable dictionary

I'm getting data from SQL server in following variables in one class:
#property(retain,nonatomic) NSString* trainingName;
#property(retain,nonatomic) NSNumber* trainingCount;
In other class,I want to append this value in NSMutableArray and finally make a dictonary.I'm doing this as following:
-(void)getTrainingDetails
{
MyTestSp_GetTrainingCountsList *objReturnTrainings = [MyTestSp_GetTrainingCounts findAll];
NSMutableArray *trainingNames = [[NSMutableArray alloc]init];
NSMutableArray *trainingCounts = [[NSMutableArray alloc]init];
NSMutableDictionary *dictTrainings = [[NSMutableDictionary alloc]init];
if ([objReturnTrainings length] > 0)
{
for (MyTestSp_GetTrainingCounts *obj in objReturnTrainings)
{
// get the values and assign to NSMutable array
trainingNames = trainingName;
trainingCounts = trainingCount;
//Make the dictionary.
}
}
}
Is this the correct way of doing and how can I put this in dictionary?
Please help.
You appear to be trying to set your array directly to your number / string (which you aren't actually getting out of obj so your code shouldn't compile...). You also don't need the arrays to create the dictionary. You can just do:
for (MyTestSp_GetTrainingCounts *obj in objReturnTrainings)
{
dictTrainings[obj.trainingName] = obj.trainingCount;
}

Copy C pointers to NSMutableDictionary

I have a class that parses through an XML file in iOS.
You can get the data of an element in the form of an TBXMLElement*.
I want to iterate through the XML and make deep copies of the TBXMLElements and store them in an NSMutableDictionary class variable.
How can I:
myClassDict addObject:(TBXMLElement*)element?
You can put the pointers in an NSValue. What key are you going to use?
// Save the TBXMLElement*
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setValue:[NSValue valueWithPointer:element] forKey:#"whatKey"];
…
// Get the TBXMLElement*
TBXMLElement *el = (TBXMLElement *)[[dict valueForKey:#"whatKey"] pointerValue];
Like said in the comments, you will have to wrap TBXMLElement* in a subclass of NSObject. Probably something like:
#interface MyXMLElement {
TBXMLElement* _xmlElement;
}
-(void)setXMElement:(TBXMLelement*)element;
#end
You can then populate the element:
MyXMLElement *elmt = [[MyXMLElement alloc] init];
[emlt setXMLElement:pointerToTBXMLElement];
[someArray addObject:elmt];

NSMutableDictionary -- using allKeysforObject not retrieving array values

NSMutableDictionary *expense_ArrContents = [[NSMutableDictionary alloc]init];
for (int i = 1; i<=4; i++) {
NSMutableArray *current_row = [NSMutableArray arrayWithObjects:#"payer_id",#"Expense_Type_id",#"Category_Id",#"SubCategory_Id",nil];
[expense_ArrContents setObject:current_row forKey: [NSNumber numberWithInt:i]];
}
NSArray *newArray = [expense_ArrContents allKeysForObject:#"payer_id"];
NSLog(#"%#",[newArray description]);
i want to get the list of key values containing the particular object which is in the array of values stored in nsmutabledictionary for a particular key.
In the line where you get all the keys ([expense_ArrContents allKeysForObject:#"payer_id"];) you actually get keys for an object that is not in any of the array's items. This #"player_id" is different object than the #"player_id" you added in current_row. In fact, maybe all of your rows have different #"player_id" objects (except if the compiler has made some optimization - maybe it threats that same string literal as one object instead of creating new object for each iteration).
Try creating an NSString object for the #"player_id" which you add to the current_row and then get all the keys for that same object:
NSString* playerId = #"player_id";
for(){
NSMutableArray *current_row = [NSMutableArray arrayWithObjects: playerId,...];
...
}
NSArray *newArray = [expense_ArrContents allKeysForObject:playerId];
Your NSArray *newArray = [expense_ArrContents allKeysForObject:#"payer_id"]; will not return any value because in expense_ArrContents there is no such key(#"payer_id"), instead there are keys like 1,2,3 etc.What is your requirement?Want to see what all keys are there in expense_ArrContents just log
NSArray*keys=[expense_ArrContents allKeys];
Try this :
NSMutableArray *array_key=[[NSMutableArray alloc]init];
for (NSString *key in expense_ArrContents) {
if ([[expense_ArrContents objectForKey:key] containsObject:#"payer_id"]) {
[array_key addObject:key];
}
}

Resources