Trouble with simple Array - Cocoa - objective-c

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])
}

Related

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

How to produce 2 dimensional Array in 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];
}

Replace content of NSMutableArray with NSArray

I'm working on an app that needs to retrieve some data from a server. I have created a "Server" class which handles all the communication and has a NSMutableArray *sessionData variable where I would like to store the data coming from the server (btw, is this approach correct?).
I have the data in an NSArray. I would like the NSMutableArray to have the same content of the NSArray but I didn't find any way to do this (sessionData = requestResult).
(subquestion: do I have to initialize in some way the NSMutableArray before using ? I have only declared it with #property and #synthesize)
The code you tried (from the comment) should have worked. The reason it did not work is that your sessionData was nil.
You need to initialize your sessionData - set it to [NSMutableArray array] in the initializer; then your code
[sessionData removeAllObjects];
[sessionData setArray:result];
will work perfectly. You do not even need the first line - the second one replaces the content of sessionData with that of the result.
Try this way:
sessionData = [result mutableCopy];
[result release];
Or
NSMutableArray *sessionData = [[NSMutableArray alloc] initWithContentsOfArray:result];
Or, if you could do this:
NSMutableArray *session = [NSMutableArray arrayWithArray:someArray];
1. is this approach correct?
Yes.
2. I didn't find any way to do this (sessionData = requestResult)
As many have suggested you can use mutableCopy to assign requestResult to sessionData
OR you can use arrayWithArray as one answer suggests.
3. do I have to initialize in some way the NSMutableArray before using ?
Yes. If you are changing any variable it must have memory allocated.
In your example something like this:
NSArray *requestData = [[NSArray alloc] initWithObjects:#"3", #"4", #"5", nil];
_sessionData = [[NSMutableArray alloc] initWithArray:requestData];
[requestData release];
NSLog(#"%#", [sessionData objectAtIndex:0]); // 2012-03-30 15:53:39.446 <app name>[597:f803] 3
NSLog(#"count: %d", [sessionData count]); //2012-03-30 15:53:39.449 <app name>[597:f803] count: 3

Assigning NSDictionary keys to NSStrings

I'm importing a txt file with a list of first and last names. Each new name is on it's own line, so I imported them into a NSMutableArray and then split them with componentsSeparatedByString:#"\n". I then want to sort the names via their last name. I have found this Sort collections, but I'm lost at how I would tell my NSStrings that are within my Array to have the key's firstName and lastName. Obviously I'd have to make an NSDictionary, but can you do a for loop where by I say something like anything before the " " (space) is firstName, and anything after is the lastName.
Hopefully I've been clear enough,
Thanks in advance.
EDIT: This is all going to be displayed in a UITableView, if that changes/helps.
Personally, I would make a simple class called Name that has a property for firstName and a property for lastName. You can then loop through the array and to create your Name instances, add them to an NSMutableArray and then sort the array. You can go the dictionary route if you want of course.
Here is an example:
NSMutableArray *namesList = [NSMutableArray arrayWithCapacity:0];
for (NSString *name in originalArray) {
NSArray *tempArray = [name componentsSeparatedByString:#" "];
Name *newNameInstance = [[Name alloc] init];
newNameInstance.firstName = [tempArray objectAtIndex:0];
newNameInstance.lastName = [tempArray objectAtIndex:1];
[namesList addObject:newNameInstance];
}
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:#"lastName"
ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [namesList sortedArrayUsingDescriptors:sortDescriptors];
This code hasn't been checked but it should work. I haven't taken care with memory management so please be mindful of that.
Update
Sorry, should be [tempArray objectAtIndex:0]. Fixed it above.
Since firstName and lastName are strings then they should be declared as NSString. Try not to use id for a property unless you have a really good reason.
Update 2
If you want to check the values do this:
for (Name *name in sortedArray) {
NSLog(#"%#", name.firstname);
NSLog(#"%#", name.lastName);
}

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.