How to produce 2 dimensional Array in Objective C - objective-c

How do i produce a 2 dimensional NSMutable array as this:
Array:
=>[item1]=>[item1a,item1b,item1c...]
=>[item2]=>[item2a,item2b,item2c...]
...
=>[item10]=>[item10a,item10b,item10c...]
So far i've only been successful up to the [item1]=>[item1a,item1b,item1c...]
When i try to add more 2 dimensional array it keeps overriding the first row.

Create NSMutableArray and assign NSMutableArrays to it as its objects.
For example:
NSMutableArray * myBig2dArray = [[NSMutableArray alloc] init];
// first internal array
NSMutableArray * internalElement = [[[NSMutableArray alloc] init] autorelease];
[internalElement addObject:#"First - First"];
[internalElement addObject:#"First - Second"];
[myBig2dArray addObject:internalElement];
// second internal array
internalElement = [[[NSMutableArray alloc] init] autorelease];
[internalElement addObject:#"Second - First"];
[internalElement addObject:#"Second - Second"];
[myBig2dArray addObject:internalElement];

To make a 2 dimensional array you would make an array of arrays.
NSArray *2darray = [NSArray arrayWithObjects: [NSArray arrayWithObjects: #"one", #"two", nil], NSArray arrayWithObjects: #"one_2", #"two_2", nil]];
It gets very verbose but that is the way I know how to do this. An array of dictionaries may be better for your situation depending on what you need.

I wrote an NSMutableArray wrapper for easy use as a Two Dimensional array. It is available on github as CRL2DArray here . https://github.com/tGilani/CRL2DArray

First you to have set An NSMutableDictionary on .h file
#interface MSRCommonLogic : NSObject
{
NSMutableDictionary *twoDimensionArray;
}
then have to use following functions in .m file
- (void)setValuesToArray :(int)rows cols:(int) col value:(id)value
{
if(!twoDimensionArray)
{
twoDimensionArray =[[NSMutableDictionary alloc]init];
}
NSString *strKey=[NSString stringWithFormat:#"%dVs%d",rows,col];
[twoDimensionArray setObject:value forKey:strKey];
}
- (id)getValueFromArray :(int)rows cols:(int) col
{
NSString *strKey=[NSString stringWithFormat:#"%dVs%d",rows,col];
return [twoDimensionArray valueForKey:strKey];
}

Related

Trouble with simple Array - Cocoa

I was wondering to know if there is any possibility to do the following:
I have a method like:
one = [[NSMutableArray alloc] initWithObjects:#"1",#"2",#"3", nil];
two = [[NSMutableArray alloc] initWithObjects:#"4",#"5",#"6", nil];
-(void)getStringAndChooseArray:(NSString *)nameOfArray {
//What i want to do is something like:
NSLog(#"The array %# has got %i objects",nameOfArray,[nameOfArray count])
//Of course it is giving me an error since nameOfArray is a string..
//I know it is hard to understand,
//but what I'm trying to do is to call this method
//pass a string variable, which is named as one of the two arrays,
//and using it to do the rest..
}
How to use a string to identify an array and manipulate it ?
Thanks in advance !
Store your arrays in a dictionary and use the names you want to reference them by as their related keys.
Use a dictionary to map arrays to strings and then you can use them:
one = [[NSMutableArray alloc] initWithObjects:#"1",#"2",#"3", nil];
two = [[NSMutableArray alloc] initWithObjects:#"4",#"5",#"6", nil];
NSDictionary *mapping = [NSDictionary dictionaryWithObjectsAndKeys:#"one",one,#"two",two,nil];
-(void)getStringAndChooseArray:(NSString *)nameOfArray {
NSArray *array = [mapping objectForKey:nameOfArray];
NSLog(#"The array %# has got %i objects",array,[array count])
}

Sort NSMutableArray based on strings from another NSArray

I have an NSArray of strings that I want to use as my sort order:
NSArray *permissionTypes = [NSArray arrayWithObjects:#"Read", #"Write", #"Admin", nil];
I then have a NSMutableArray that may or may not have all three of those permissions types, but sometimes it will only be 2, sometimes 1, but I still want it sorted based on my permissionsTypes array.
NSMutableArray *order = [NSMutableArray arrayWithArray:[permissions allKeys]];
How can I always sort my order array correctly based on my using the permissionTypes array as a key?
I would go about this by creating a struct or an object to hold the permission types.
Then you can have...
PermissionType
--------------
Name: Read
Order: 1
PermissionType
--------------
Name: Write
Order: 2
and so on.
Then you only need the actual array of these objects and you can sort by the order value.
[array sortUsingComparator:^NSComparisonResult(PermissionType *obj1, PermissionType *obj2) {
return [obj1.order compare:obj2.order];
}];
This will order the array by the order field.
NSMutableArray *sortDescriptors = [NSMutableArray array];
for (NSString *type in permissionTypes) {
NSSortDescriptor *descriptor = [[[NSSortDescriptor alloc] initWithKey:type ascending:YES] autorelease];
[sortDescriptors addObject:descriptor];
}
sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];
Use whichever sorting method on NSMutableArray you prefer, you will either provide a block or a selector to use for comparing two elements. In that block/selector rather than comparing the two strings passed in directly look each up in your permissionTypes array using indexOfObject: and compare the resulting index values returned.
I suggest you another approuch:
- (void)viewDidLoad
{
[super viewDidLoad];
arrayPermissions = [[NSMutableArray alloc] init];
NSDictionary *dicRead = [NSDictionary dictionaryWithObjectsAndKeys:
#"Read", #"Permission", nil];
NSDictionary *dicWrite = [NSDictionary dictionaryWithObjectsAndKeys:
#"Write", #"Permission", nil];
NSDictionary *dicAdmin = [NSDictionary dictionaryWithObjectsAndKeys:
#"Admin", #"Permission", nil];
NSLog(#"my dicRead = %#", dicRead);
NSLog(#"my dicWrite = %#", dicWrite);
NSLog(#"my dicAdmin = %#", dicAdmin);
[arrayPermissions addObject:dicRead];
[arrayPermissions addObject:dicWrite];
[arrayPermissions addObject:dicAdmin];
NSLog(#"arrayPermissions is: %#", arrayPermissions);
// create a temporary Dict again
NSDictionary *temp =[[NSDictionary alloc]
initWithObjectsAndKeys: arrayPermissions, #"Permission", nil];
// declare one dictionary in header class for global use and called "filteredDict"
self.filteredDict = temp;
self.sortedKeys =[[self.filteredDict allKeys]
sortedArrayUsingSelector:#selector(compare:)];
NSLog(#"sortedKeys is: %i", sortedKeys.count);
NSLog(#"sortedKeys is: %#", sortedKeys);
}
hope help

NSArray filled with bool

I am trying to create an NSArray of bool values. How many I do this please?
NSArray *array = [[NSArray alloc] init];
array[0] = YES;
this does not work for me.
Thanks
NSArrays are not c-arrays. You cant access the values of an NSArray with array[foo];
But you can use c type arrays inside objective-C without problems.
The Objective-C approach would be:
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:[NSNumber numberWithBool:YES]];
//or
[array addObject:#(NO)];
...
BOOL b = [[array objectAtIndex:0] boolValue];
....
[array release];
EDIT: New versions of clang, the now standard compiler for objective-c, understand Object subscripting. When you use a new version of clang you will be able to use array[0] = #YES
Seems like you've confused c array with objc NSArray. NSArray is more like a list in Java, into which you can add objects, but not values like NSInteger, BOOL, double etc. If you wish to store such values in an NSArray, you first need to create a mutable array:
NSMutableArray* array = [[NSMutableArray alloc] init];
And then add proper object to it (in this case we'll use NSNumber to store your BOOL value):
[array addObject:[NSNumber numberWithBool:yourBoolValue]];
And that's pretty much it! If you wish to access the bool value, just call:
BOOL yourBoolValue = [[array objectAtIndex:0] boolValue];
Cheers,
Pawel
Use [NSNumber numberWithBool: YES] to get an object you can put in the collection.

How to deal with booleans in NSMutableArrays?

Can someone tell me why my application crashes here ?
and why it does not crash when i replace the YES objects with NSString values ?
all i want to do is to store boolean data into array and to modify these data later,
can someone please tell me how to do this ?
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray* arr = [[NSMutableArray alloc] initWithObjects:YES, YES, YES, YES, nil];
NSLog([arr objectAtIndex:1]);
}
YES and NO are BOOLs, which is not an Objective-C class. Foundation containers can only store Objective-C objects.
You need to wrap them in an NSNumber, like:
NSNumber* yesObj = [NSNumber numberWithBool:YES];
NSMutableArray* arr = [[NSMutableArray alloc] initWithObjects:
yesObj, yesObj, yesObj, yesObj, nil];
NSLog(#"%d", [[arr objectAtIndex:1] boolValue]);
The reason why it accepts NSString is because an NSString is a kind of Objective-C class.

Can a function return an object? Objective-C and NSMutableArray

I have an NSMutableArray. It's members eventually become members of an array instance in a class. I want to put the instantiantion of NSMutable into a function and to return an array object. If I can do this, I can make some of my code easier to read. Is this possible?
Here is what I am trying to figure out.
//Definition:
function Objects (float a, float b) {
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:[NSNumber numberWithFloat:a]];
[array addObject:[NSNumber numberWithFloat:b]];
//[release array]; ????????
return array;
}
//Declaration:
Math *operator = [[Math alloc] init];
[operator findSum:Objects(20.0,30.0)];
My code compiles if I instantiate NSMutableArray right before I send the message to the receiver. I know I can have an array argument along with the method. What I have problem seeing is how to use a function and to replace the argument with a function call. Any help is appreciated. I am interested in the concept not in suggestions to replace the findSum method.
Use autorelease to return objects you create in methods/functions.
NSMutableArray* Objects(float a, float b) {
NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
// or: [NSMutableArray array];
[array addObject:[NSNumber numberWithFloat:a]];
[array addObject:[NSNumber numberWithFloat:b]];
return array;
}
Or simply:
NSMutableArray* Objects(float a, float b) {
return [NSMutableArray arrayWithObjects:
[NSNumber numberWithFloat:a],
[NSNumber numberWithFloat:b],
nil];
}