how to copy array? - objective-c

I have four arrays as follows:
toArray = [[NSMutableArray alloc] initWithObjects:#"to 1",#"to 2",#"to 3",#"to 4",#"to 5",#"to 6",#"to 7",nil];
fromArray = [[NSMutableArray alloc] initWithObjects:#"from 1",#"from 2",#"from 3",#"from 4",#"from 5",#"from 6",#"from 7",nil];
messageArray = [[NSMutableArray alloc] initWithObjects:#"message 1",#"message 2",#"message 3",#"message 4",#"message 5",#"message 6",#"message 7",nil];
dayArray = [[NSMutableArray alloc] initWithObjects:#"day 1",#"day 2",#"day 3",#"day 4",#"day 5",#"day 6",#"day 7",nil];
I want to copy or create a single array which should contain all these 4 arrays.
How can i achieve it?

Your question is a little ambiguous; how do you want the result?
NSMutableArray *completeArray = [NSMutableArray array];
[completeArray addObjectsFromArray:toArray];
[completeArray addObjectsFromArray:fromArray];
[completeArray addObjectsFromArray:messageArray];
[completeArray addObjectsFromArray:dayArray];
Or
NSMutableArray *completeArray = [NSMutableArray arrayWithObjects:toArray, fromArray, messageArray, dayArray, nil];
Or if all arrays have the same number of elements:
NSMutableArray *completeArray = [NSMutableArray array];
for (NSUInteger i = 0; i < [toArray count]; i++)
{
NSString *fullString = [NSString stringWithFormat:#"%# %# %# %#", [toArray objectAtIndex:i], [fromArray objectAtIndex:i], [messageArray objectAtIndex:i], [dayArray objectAtIndex:i]];
[completeArray addObject:fullString];
}
Or, as an array of dictionaries (also assuming all arrays are same length):
NSMutableArray *completeArray = [NSMutableArray array];
for (NSUInteger i = 0; i < [toArray count]; i++)
{
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
[toArray objectAtIndex:i], #"to",
[fromArray objectAtIndex:i], #"from",
[messageArray objectAtIndex:i], #"message",
[dayArray objectAtIndex:i], #"day",
nil];
[completeArray addObject:dict];
}

This should work:
NSArray *singleArray = [NSArray arrayWithElements:toArray, fromArray, messsageArray, dayArray, nil];
// mind the nil element at the end

NSMutableArray *result = [NSMutableArray arrayWithCapacity:0];
[result addObjectsFromArray:toArray];
[result addObjectsFromArray:fromArray];
[result addObjectsFromArray:messageArray];
[result addObjectsFromArray:dayArray];

Related

Create NSMutableArray by a NSString value

How I can create a NSMutableArray (name) dynamically by a NSString value?
e.g. NSString *stringName = #"helloArray1";
Then create the NSMutableArray with the "helloArray1" dynamically.
e.g. NSMutableArray * (--here the stringName / helloArray1---) = [NSMutableArray new];
And then the NSLog:
NSLog(#"%#", (--here the stringName / helloArray1---) );
Thanks for your help
I think that's not possible.
Better is set dynamically all into object. For example:
NSMutableDictionary *variables = [NSMutableDictionary new];
for (int i = 0; i < 10; i++) {
NSMutableArray *temp = [[NSMutableArray alloc] initWithObjects:#"1", #"2", nil];
[variables setObject:temp forKey:[NSString stringWithFormat:#"value_%d", i]];
}
NSLog(#"%#", [variables objectForKey:#"value_1"]);

How do i create an array of index from an array which has my chosen objects?

NSMutableArray *myIdentityArray = [[NSMutableArray alloc]initWithObjects:#"3",#"1", #"2",#"0", #"0", #"1",#"3",#"1", #"2",#"0", #"0", #"1", nil];
Now How do i create an Array1 with all index that has object 1. for this case it will have 1 , 5, 7 and 11 as its element?
You can use indexOfObject:inRange: method on your NSMutableArray
check this code:
NSMutableArray *myIdentityArray = [[NSMutableArray alloc]initWithObjects:#"3",#"1", #"2",#"0", #"0", #"1",#"3",#"1", #"2",#"0", #"0", #"1", nil];
NSMutableArray * array1 = [NSMutableArray array];
NSUInteger loc = 0;
NSUInteger len = myIdentityArray.count;
NSRange range = NSMakeRange(loc, len);
NSUInteger idx = [myIdentityArray indexOfObject:#"1" inRange:range];
while (idx != NSNotFound) {
[array1 addObject:[NSNumber numberWithUnsignedInteger:idx]];
loc = idx +1;
len = myIdentityArray.count - loc;
range = NSMakeRange(loc, len);
idx = [myIdentityArray indexOfObject:#"1" inRange:range];
}
NSLog(#"%#",array1);
You have to use if condition to check the value of each object, then store the index of the object in the array.
Refer this: Search NSArray for value matching value
Do this with a simple loop:
NSMutableArray *myIdentityArray = #[ #"3", #"1", #"2", #"0", #"0", #"1", #"3", #"1", #"2", #"0", #"0", #"1" ];
NSString *search = #"1";
NSMutableArray *results = [NSMutableArray array];
NSInteger index = 0;
for (NSString *str in myIdentityArray) {
if ([str isEqualToString:search]) {
[results addObject:#(index)];
}
index++;
}
NSLog(#"results = %#", results);

Twodimensional array into a UILabel

I have a twodimensional array where i i would like to print all second values of the objects into an UIlabel homePlayersFouls. the problem is i do not know how to this.
I have tried following things:
componentsJoinedByString:#"\n".
This will just print (
The other thing ive tried is this:
[[homePlayersArray objectAtIndex:i] objectAtIndex:1];
this just prints 0 since it looping and deleting the content inside label
i've checked wether there is something wrong the the array, but when i do this inside the loop:
nslog(#"%#",[[homePlayersArray objectAtIndex:i] objectAtIndex:1];);
It prints all 0 0 0 which is the 3 second values in my objects.
The question is then how can i print all my second values in all the objects in the array into an UIlabel?
here is the complete code:
for (int i=0;i<[homeNumbersArray count];i++){
NSArray *tempArray = [[NSArray alloc] initWithObjects:[homeNumbersArray objectAtIndex:i],[NSNumber numberWithInt:0], nil];
[homePlayersArray addObject:tempArray];
NSObject* someObject = [[homePlayersArray objectAtIndex:i] objectAtIndex:1];
homePlayersFouls.text = [NSString stringWithFormat:#"%#", someObject];
}
You need:
homePlayersFouls.text = [homePlayersFouls.text stringByAppendingString:[NSString stringWithFormat:#"%#", someObject]];
NSMutableString *fouls = [NSMutableString string];
for (int i=0;i<[homeNumbersArray count];i++){
NSArray *tempArray = [[NSArray alloc] initWithObjects:[homeNumbersArray objectAtIndex:i],[NSNumber numberWithInt:0], nil];
[homePlayersArray addObject:tempArray];
NSObject* someObject = [[homePlayersArray objectAtIndex:i] objectAtIndex:1];
[fouls appendFormat:#"%#", someObject];
}
homePlayersFouls.text = fouls;

Objective-C: Sort keys of NSDictionary based on dictionary entries

OK so I know that dictionaries can't be sorted. But, say I have NSMutableArray *keys = [someDictionary allKeys]; Now, I want to sort those keys, based on the corresponding values in the dictionary (alphabetically). So if the dictionary contains key=someString, then I want to sort keys based on the strings they correspond to. I think its some application of sortUsingComparator but its a little out of my reach at this point.
NSArray *keys = [someDictionary allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSString *first = [someDictionary objectForKey:a];
NSString *second = [someDictionary objectForKey:b];
return [first compare:second];
}];
NSDictionary *dict = // however you obtain the dictionary
NSMutableArray *sortedKeys = [NSMutableArray array];
NSArray *objs = [dict allValues];
NSArray *sortedObjs = [objs sortedArrayUsingSelector:#selector(compare:)];
for (NSString *s in sortedObjs)
[sortedKeys addObjectsFromArray:[dict allKeysForObject:s]];
Now sortedKey will contain the keys sorted by their corresponding objects.
Sort keys of NSDictionary based on dictionary keys
Abobe is for returning a sorted array with based on dictionary content, this is for returning an array sorted by dictionary key:
NSArray *keys = [theDictionary allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
return [a compare:b];
}];
NSMutableArray *sortedValues = [NSMutableArray new];
for(NSString *key in sortedKeys)
[sortedValues addObject:[dictFilterValues objectForKey:key]];
Just write it here cause I didn't find it anywhere: To get an alphanumeric sorted NSDictionary back from an NSDictionary based on the value - which in my case was neccessary - you can do the following:
//sort typeDict alphanumeric to show it in order of values
NSArray *keys = [typeDict allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSString *first = [typeDict objectForKey:a];
NSString *second = [typeDict objectForKey:b];
return [first compare:second];
}];
NSLog(#"sorted Array: %#", sortedKeys);
NSMutableDictionary *sortedTypeDict = [NSMutableDictionary dictionary];
int counter = 0;
for(int i=0; i < [typeDict count]; i++){
NSString *val = [typeDict objectForKey:[sortedKeys objectAtIndex:counter]];
NSString *thekey = [sortedKeys objectAtIndex:counter];
[sortedTypeDict setObject:val forKey:thekey];
counter++;
}
NSLog(#"\n\nsorted dict: %#", sortedTypeDict);
Not a big deal!
If any value from the dictionary is null then use this code
NSArray *keys = [typeDict allKeys];
NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
NSArray *sortedKeys = [keys sortedArrayUsingDescriptors:#[sd]];
NSLog(#"SORT 1 %#",sortedKeys);
NSMutableDictionary *sortedTypeDict = [NSMutableDictionary dictionary];
int counter = 0;
for(int i=0; i < [typeDict count]; i++){
id val = [typeDict objectForKey:[sortedKeys objectAtIndex:counter]];
NSString *thekey = [sortedKeys objectAtIndex:counter];
[sortedTypeDict setObject:val forKey:thekey];
counter++;
}
NSLog(#"\n\nsorted dict: %#", sortedTypeDict);

algorithm to add randomly-generated NSStrings to NSMutableArray

The goal is to generate an NSString chars in length and assign each string to an array. I'm getting stuck on what I need to do with my algorithm to get the correct result. Here's the sample. The result I get is the same randomly generated string added to my array 26 times instead of 26 DIFFERENT strings added.
I've thought about declaring 26 different NSStrings and assigning each result from the algorithm to each string, but that seems inefficient. Thanks for the help.
NSMutableString *string = #"expert";
NSUInteger strLength = [string length];
NSString *letterToAdd;
NSString *finishedWord;
NSMutableString *randomString = [NSMutableString stringWithCapacity: strLength];
NSMutableArray *randomArray = [[NSMutableArray alloc] init];
NSArray *charArray = [[NSArray alloc] initWithObjects: #"a", #"b", #"c", #"d",
#"e", #"f", #"g", #"h", #"i", #"j", #"k", #"l", #"m",
#"o", #"p", #"q", #"r", #"s", #"t", #"u", #"v", #"w",
#"x", #"y", #"z", nil];
for (int a = 0; a < 26; a++) {
for (int i = 0; i < strLength; i++) {
letterToAdd = [charArray objectAtIndex: arc4random() % [charArray count]];
if([randomString length] < strLength) {
[randomString insertString: letterToAdd atIndex: i];
}
finishedWord = randomString;
}
[randomArray addObject: finishedWord];
}
NSLog(#"Random Array count %i, contents: %#", [randomArray count], randomArray);
Here's how I would do it:
#import "NSString+Shuffle.h"
NSString * string = #"expert";
NSUInteger strLength = [string length];
NSString * alphabet = #"abcdefghijklmnopqrstuvwxyz";
NSMutableSet * randomWords = [NSMutableSet set];
while ([randomWords count] < 26) {
NSString * newWord = [alphabet shuffledString];
newWord = [newWord substringToIndex:strLength];
[randomArray addObject:newWord];
}
NSLog(#"Random set count %d, contents: %#", [randomWords count], randomWords);
You'd then need a category on NSString that defines shuffledString. This method would simply take the characters in the string and rearrange them randomly. Decent shuffle algorithms can be found quite easily with Google.
I hope you get the basic idea of how this works. The only modification I made is using an NSSet instead of an NSArray, and what the conditional on the loop is. The eliminates the (slim) possibility of duplicate random words.
Edit: since I'm feeling generous, here's a basic shuffledString implementation:
//NSString+Shuffle.h
#interface NSString (ShuffleAdditions)
- (NSString *) shuffledString;
#end
//NSString+Shuffle.m
#import "NSString+Shuffle.h"
#implementation NSString (ShuffleAdditions)
- (NSString *) shuffledString {
NSMutableString * shuffled = [self mutableCopy];
NSUInteger length = [shuffled length];
for (int i = 0; i < (4*length); ++i) {
NSString * randomChar = [shuffled subStringWithRange:NSMakeRange(arc4random() % (length-1), 1)];
[shuffled appendString:randomChar];
}
return [shuffled autorelease];
}
#end
You should create a new randomString each time:
NSMutableString *string = #"expert";
NSUInteger strLength = [string length];
NSString *letterToAdd;
NSString *finishedWord;
//NSMutableString *randomString = [NSMutableString stringWithCapacity: strLength];
NSMutableArray *randomArray = [[NSMutableArray alloc] init];
NSArray *charArray = [[NSArray alloc] initWithObjects: #"a", #"b", #"c", #"d", #"e", #"f",
#"g", #"h", #"i", #"j", #"k", #"l", #"m", #"o", #"p", #"q", #"r", #"s",
#"t", #"u", #"v", #"w", #"x", #"y", #"z", nil];
for (int a = 0; a < 26; a++) {
NSMutableString *randomString = [NSMutableString stringWithCapacity: strLength];
for (int i = 0; i < strLength; i++) {
letterToAdd = [charArray objectAtIndex: arc4random() % [charArray count]];
//if([randomString length] < strLength) {
[randomString insertString: letterToAdd atIndex: i];
//}
//finishedWord = randomString;
}
//[randomArray addObject: finishedWord];
[randomArray addObject: randomString];
}
NSLog(#"Random Array count %i, contents: %#", [randomArray count], randomArray);
You're adding the same object to your array every time through the loop, and overwriting it as you go. You mentioned:
I've thought about declaring 26 different NSStrings and assigning each
result from the algorithm to each string...
And that is indeed exactly what you need to do. Moving the initialization of randomString into the loop will solve your problem (getting a new NSMutableString on every loop iteration, rather than using a single object). Change the definition of randomString to a simple type definition:
NSMutableString *randomString;
and then in your outer loop, add this line:
randomString = [NSMutableString stringWithCapacity:strLength];
You shouldn't need to change any of the rest of your code.