hash of array in objective-c, how? - objective-c

How is a hash of integer array can be represented in objective-c? Here is the ruby hash as an example:
hi_scores = { "John" => [1, 1000],
"Mary" => [2, 8000],
"Bob" => [5, 2000] }
such that can be accessed by:
puts hi_scores["Mary"][1]
=> 8000
hopefully easy to serialize too. Thanks!

NSDictionary * highScores = [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:1000], nil], #"John",
[NSArray arrayWithObjects:[NSNumber numberWithInt:2], [NSNumber numberWithInt:8000], nil], #"Mary",
[NSArray arrayWithObjects:[NSNumber numberWithInt:5], [NSNumber numberWithInt:2000], nil], #"Bob", nil];
NSLog(#"%#", [[highScores objectForKey:#"Mary"] objectAtIndex:1]);

You're looking for a data structure called a map / associative array.
Take a look at this question:
HashTables in Cocoa

Related

formatting dictionary values

I am needing to store values in a dictionary in the following format:
{ "UserId": 123,
"UserType": "blue",
"UserActs": [{
"ActId": 3,
"Time": 1
}, {
"ActId": 1,
"Time": 6
}]
}
I know I'll need a dictionary for the intitial values and a nested one for the UserActs but I am unsure how to store seperate values for the same keys "ActId" and "Time". How would I go about adding them in the dictionary following this format?
This is the old, long winded, way of creating that dictionary (there is a new syntax, using Objective-C literals, however they are not mutable, so I chose this method):
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[NSNumber numberWithInt:123] forKey:#"UserId"];
[dict setObject:#"blue" forKey:#"UserType"];
NSMutableArray *acts = [[NSMutableArray alloc] init];
[acts addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:3], #"ActId",
[NSNumber numberWithInt:1], #"Time",
nil]];
[acts addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:1], #"ActId",
[NSNumber numberWithInt:6], #"Time",
nil]];
[dict setObject:acts forKey:#"UserActs"];
You can also use the shorthand for arrays and dictionaries
NSDictionary * dictionary = #{ #"UserId": #123,
#"UserType": #"blue",
#"UserActs": #[#{
#"ActId": #3,
#"Time": #1
}, #{
#"ActId": #1,
#"Time": #6
}]
};

Objective-c SBJSONWriter convert array of dictionaries to JSON

I'm having some trouble with SBJsonWriter at the moment.
I need to send a request that contains a json object of name/value pairs. e.g.
[{%22uid%22:1,%22version%22:1}]
I can't figure out how to do this in Obj-C with the SBJson Writer framework.
For each pair I have tried to construct a dictionary then add the dictionary to an array. This results in an array containing many dictionaries, each containing one name/value pair.
Any idea on how a fix for this or is it possible?
Thanks in advance
To produce an Objective-C structure equivalent to the above JSON you should do this:
NSArray* json = [NSArray arrayWithObject: [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt: 1], #"uid",
[NSNumber numberWithInt: 1], #"version",
nil]];
Check my answer to the '' SBJsonWriter Nested NSDictionary '' question. it illustrates how to properly use SBJsonWriter.
It includes error check and some pieces of advise about SBJsonWriter behaviour with NSDate, float, etc..
Excerpt:
NSDictionary* aNestedObject = [NSDictionary dictionaryWithObjectsAndKeys:
#"nestedStringValue", #"aStringInNestedObject",
[NSNumber numberWithInt:1], #"aNumberInNestedObject",
nil];
NSArray * aJSonArray = [[NSArray alloc] initWithObjects: #"arrayItem1", #"arrayItem2", #"arrayItem3", nil];
NSDictionary * jsonTestDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"stringValue", #"aString",
[NSNumber numberWithInt:1], #"aNumber",
[NSNumber numberWithFloat:1.2345f], #"aFloat",
[[NSDate date] description], #"aDate",
aNestedObject, #"nestedObject",
aJSonArray, #"aJSonArray",
nil];

How can I access this variable Globally in Objective C?

Here is the code im having issues with:
if(DriveInfoDict) {
NSLog(#"%#", DriveInfoDict);
//PrevSpeedsDict = [DriveInfoDict objectForKey: #"speed"];
//NSLog(#"Previous Speed Dict:%#", PrevSpeedsDict);
}
DriveInfoDict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble: CurrentLatitude], #"Lat",
[NSNumber numberWithDouble: CurrentLongitude], #"Long",
[NSNumber numberWithDouble:speedMPH], #"speed",
nil];
Here, I would like to set DriveInfoDict, so that the next time the function runs it will have the previous value. I have stripped the operators to simplify my problem.
The error I am getting is : EXC-BAD-ACCESS
I am new to Obj-C and I do not know how to make this object accessible here. Some code with explanation as to if it goes in the H or M file would be very helpful.
You need to retain the dictionary or use alloc/init (which returns a retained dictionary. So either:
DriveInfoDict = [[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble: CurrentLatitude], #"Lat",
[NSNumber numberWithDouble: CurrentLongitude], #"Long",
[NSNumber numberWithDouble:speedMPH], #"speed",
nil] retain];
or:
DriveInfoDict = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithDouble: CurrentLatitude], #"Lat",
[NSNumber numberWithDouble: CurrentLongitude], #"Long",
[NSNumber numberWithDouble:speedMPH], #"speed",
nil];
If you replace the content of DriveInfoDict (that is: assign a new dictionary) don't forget to first release it.

sorting 2D arrays in Objective C

I'm stuck with sorting 2D arrays in objective c. I have a 2D array which I made from two string arrays.
NSArray *totalRatings = [NSArray arrayWithObjects:namesArray,ratingsArray,nil];
I've pulled the values using:
for (int i=0; i<2; i++) {
for (int j=0; j<5; j++) {
NSString *strings = [[totalRatings objectAtIndex:i] objectAtIndex:j];
NSLog(#"i=%i, j=%i, = %# \n",i,j,strings);
}
}
Firstly, I wonder whether there is a more elegant method for working with the length of the totalRatings array. Secondly, here is what the totalRatings array contains:
Person 1, 12
Person 2, 5
Person 3, 9
Person 4, 10
Person 7, 2
Since these are all strings, how can these be sorted? I'm looking for:
Person 1, 12
Person 4, 10
Person 3, 9
Person 2, 5
Person 7, 2
I'd appreciate any help you can provide.
You may want to use a dictionary to deal with this data, instead of two distinct arrays.
Instead of what you have now, why don't you put the record for each person on a dictionary:
NSArray *totalRatings = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:#"Person 1", #"name", [NSNumber numberWithInt:12], #"rating", nil],
[NSDictionary dictionaryWithObjectsAndKeys:#"Person 2", #"name", [NSNumber numberWithInt:5], #"rating", nil],
[NSDictionary dictionaryWithObjectsAndKeys:#"Person 3", #"name", [NSNumber numberWithInt:9], #"rating", nil],
[NSDictionary dictionaryWithObjectsAndKeys:#"Person 4", #"name", [NSNumber numberWithInt:10], #"rating", nil],
[NSDictionary dictionaryWithObjectsAndKeys:#"Person 7", #"name", [NSNumber numberWithInt:2], #"rating", nil],
nil];
NSArray *sortedArray = [totalRatings sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"rating" ascending:NO]]];

From array of dictionaries, make array containing values of one key

I have an array of dictionaries. I would like to extract an array with all the elements of one particular key of the dictionaries in the original array. Can this be done without enumeration?
Yes, use the NSArray -valueForKey: method.
NSArray *extracted = [sourceArray valueForKey:#"a key"];
Yes, just use Key-Value Coding to ask for the values of the key:
NSArray* names = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:
#"Joe",#"firstname",
#"Bloggs",#"surname",
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
#"Simon",#"firstname",
#"Templar",#"surname",
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
#"Amelia",#"firstname",
#"Pond",#"surname",
nil],
nil];
//use KVC to get the names
NSArray* firstNames = [names valueForKey:#"firstname"];
NSLog(#"first names: %#",firstNames);