how to define 2x2 or 3X.. array in ios?
like this
[name=john , age=21 , num=1]
[name=max , age=25 , num=2]
[name=petter , age=22 , num=3]
with columns
in NSMutableArray you can only add rows with objects;
i want this array[][]
Looking at your example, I wouldn't do it with arrays, or not just arrays. I'd have an array of dictionaries or an array of custom objects with the properties name, age and num. With dictionaries:
NSArray* theArray = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:
#"john", #"name",
[NSNumber numberWithInt: 21], #"age",
[NSNumber numberWithInt: 1], #"num",
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
#"max", #"name",
[NSNumber numberWithInt: 25], #"age",
[NSNumber numberWithInt: 2], #"num",
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
#"petter", #"name",
[NSNumber numberWithInt: 22], #"age",
[NSNumber numberWithInt: 3], #"num",
nil],
nil];
How to declare a two dimensional array of string type in Objective-C? might give you an idea
So many ways ...
NSMutableArray *array = [[NSMutableArray alloc] init];
NSMutableDictionary *person = [[[NSMutableDictionary alloc] init] autorelease];
[person setObject:#"john" forKey:#"name"];
[person setObject:[NSNumber numberWithInt:21] forKey:#"age"];
...
[array addObject:person];
... or create your custom class, which does hold all person data, or struct, or ... Depends on your goal.
It looks like you should be create a proper data storage class to store this in, rather than a dictionary or something like that.
e.g.
#interface Person : NSObject {
}
#property (nonatomic, copy) NSString* Name;
#property int age;
#property int num;
#end
Then create your person instances and store them in an array. You may wich to create some connivence methods first. e.g.
[[NSArray arrayWithObjects:[Person personWithName:#"Bob",Age:1 Num:3],
[Person personWithName:#"Bob",Age:1 Num:3],
[Person personWithName:#"Bob",Age:1 Num:3],nil];
Its much clearer.
Related
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
}]
};
Which type I should use to save many objects with same key?
I should post data to server where one of parameter is suggestedTo and it contains userId.
This parameters should be more then one. So I'm confused which data type I should use to save them.
For example array or dictionary should looks like
{
#"suggestedTo" = 111,
#"suggestedTo" = 222,
#"suggestedTo" = 333,
etc.
}
This is typically handled with a dictionary of sets (or arrays if the data is ordered). So in this case, you'd have something like:
NSSet *suggestedTo = [NSSet setWithObjects:[NSNumber numberWithInt:111],
[NSNumber numberWithInt:222],
[NSNumber numberWithInt:333], nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:suggestedTo,
#"suggestedTo", nil];
You could use a dictionary of arrays
NSArray *suggestedTos = [[NSArray alloc] initWithObjects:
[NSNumber numberWithInt:111],
[NSNumber numberWithInt:222],
[NSNumber numberWithInt:333], nil];
NSDictionary *myDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
suggestedTos, #"suggestedTo", nil];
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];
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.
I'm currently using NSMutableArrays in my developments to store some data taken from an HTTP Servlet.
Everything is fine since now I have to sort what is in my array.
This is what I do :
NSMutableArray *array = [[NSMutableArray arrayWithObjects:nil] retain];
[array addObject:[NSArray arrayWithObjects: "Label 1", 1, nil]];
[array addObject:[NSArray arrayWithObjects: "Label 2", 4, nil]];
[array addObject:[NSArray arrayWithObjects: "Label 3", 2, nil]];
[array addObject:[NSArray arrayWithObjects: "Label 4", 6, nil]];
[array addObject:[NSArray arrayWithObjects: "Label 5", 0, nil]];
First column contain a Label and 2nd one is a score I want the array to be sorted descending.
Is the way I am storing my data a good one ? Is there a better way to do this than using NSMutableArrays in NSMutableArray ?
I'm new to iPhone dev, I've seen some code about sorting but didn't feel good with that.
Thanks in advance for your answers !
This would be much easier if you were to create a custom object (or at least use an NSDictionary) to store the information, instead of using an array.
For example:
//ScoreRecord.h
#interface ScoreRecord : NSObject {
NSString * label;
NSUInteger score;
}
#property (nonatomic, retain) NSString * label;
#property (nonatomic) NSUInteger score;
#end
//ScoreRecord.m
#import "ScoreRecord.h"
#implementation ScoreRecord
#synthesize label, score;
- (void) dealloc {
[label release];
[super dealloc];
}
#end
//elsewhere:
NSMutableArray * scores = [[NSMutableArray alloc] init];
ScoreRecord * first = [[ScoreRecord alloc] init];
[first setLabel:#"Label 1"];
[first setScore:1];
[scores addObject:first];
[first release];
//...etc for the rest of your scores
Once you've populated your scores array, you can now do:
//the "key" is the *name* of the #property as a string. So you can also sort by #"label" if you'd like
NSSortDescriptor * sortByScore = [NSSortDescriptor sortDescriptorWithKey:#"score" ascending:YES];
[scores sortUsingDescriptors:[NSArray arrayWithObject:sortByScore]];
After this, your scores array will be sorted by the score ascending.
You don't need to create a custom class for something so trivial, it's a waste of code. You should use an array of NSDictionary's (dictionary in ObjC = hash in other languages).
Do it like this:
NSMutableArray * array = [NSMutableArray arrayWithObjects:
[NSDictionary dictionaryWithObject:#"1" forKey:#"my_label"],
[NSDictionary dictionaryWithObject:#"2" forKey:#"my_label"],
[NSDictionary dictionaryWithObject:#"3" forKey:#"my_label"],
[NSDictionary dictionaryWithObject:#"4" forKey:#"my_label"],
[NSDictionary dictionaryWithObject:#"5" forKey:#"my_label"],
nil];
NSSortDescriptor * sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:#"my_label" ascending:YES] autorelease];
[array sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];