obj-c fetching strings from array - objective-c

i'm new to obj-c (this is my first day class eheh) and i'm trying to change a label with a random string from a multidimensional array. plus, every time the button is hitten you switch the array. i know it's a bit odd eheh… this is the IBAction:
UIButton *button = (UIButton *)sender;
NSMutableArray *firstArray = [NSMutableArray array];
[firstArray addObject:#"foo"];
NSMutableArray *secondArray = [NSMutableArray array];
[secondArray addObject:#"bar"];
NSMutableArray *frasi = [NSMutableArray array];
[frasi addObject:firstArray];
[frasi addObject:secondArray];
NSMutableArray *array = [NSMutableArray arrayWithObjects:[frasi objectAtIndex:[button isSelected]], nil];
NSString *q = [array objectAtIndex: (arc4random()% [array count] )];
NSString *lab = [NSString stringWithFormat:#"%#", q];
self.label.text = lab;
all works, but the new label is
( "foo" )
instead of just foo (without quotes)... probably i mess in the last block of code...
ty

So, you create 2 mutable arrays, then add them to a new mutable array frasi. Then you get one of those two arrays and use it as the single element (because you use arrayWithObjects: instead of arrayWithArray:) of a new array array.
So array is an array that contains a single array element (instead of an array of strings as you may believe).
When you get an object from array, it's always the same single object that was used to initialize it: either firstArray or secondArray.
So you get an array of strings where you expect a string. When using stringWithFormat:, the specifier %# is replaced with the string description of that object.
A string returns itself as its own description. But the description of an array is the list of all its elements separated with commas and surrounded by parenthesis, which is why you get ( "foo" ).
So instead or creating unneeded arrays, you may just replace all the 8th last lines with this:
NSArray *array = [button isSelected] ? secondArray : firstArray;
self.label.text = [array objectAtIndex:arc4_uniform([array count])];

Actually u have array within array
Replace this line with yours:
NSString *q = [[array objectAtIndex: (arc4random()% [array count] )] objectAtIndex:0];

Related

Trying to build polygon from NSString

So, I'm trying to build an array of CGPoints by breaking an NSString, typically look like this:
31.241854,34.788867;31.241716,34.788744;31.242547,34.787585;31.242661,34.787719
Using this code:
- (NSMutableArray *)buildPolygon:(NSString *)polygon
{
NSMutableArray *stringArray = [[NSMutableArray alloc] init];
[stringArray addObject:[polygon componentsSeparatedByString:#";"]];
NSMutableArray *polygonArray = [[NSMutableArray alloc] init];
for (int i=0; i < polygonArray.count; i++)
{
NSArray *polygonStringArray = [[NSArray alloc] init];
polygonStringArray = [[stringArray objectAtIndex:i] componentsSeparatedByString:#","];
CGFloat xCord = [[polygonStringArray objectAtIndex:0] floatValue];
CGFloat yCord = [[polygonStringArray objectAtIndex:1] floatValue];
CGPoint point = CGPointMake(xCord, yCord);
[polygonArray addObject:[NSValue valueWithCGPoint:point]];
}
NSLog(#"return polygonArray: %#", polygonArray);
return polygonArray;
}
But eventually I get an empty array.
What I'm doing wrong?
You're defining polygonArray as an empty array just before the start of your for loop. You should define polygonArray like:
NSArray *polygonArray = [polygon componentsSeparatedByString:#";"];
And you don't even need to bother with that stringArray variable.
You have confusion over alloc & init, and one simple typo...
The confusions first:
NSMutableArray *stringArray = [[NSMutableArray alloc] init];
This creates a new NSMutableArray and stores a reference to it in stringArray. All good so far.
[stringArray addObject:[polygon componentsSeparatedByString:#";"]];
And this obtains a reference to an NSArray ([polygon componentsSeparatedByString:#";"]) and adds it as a single element to the mutable array referenced by stringArray. There is nothing wrong per se with this, but it is not what you want in this case - you just want the array returned by componentsSeparatedByString:. You do this with:
NSArray *stringArray = [polygon componentsSeparatedByString:#";"];
Which takes the reference returned by componentsSeparatedByString: and stores it in the variable stringArray - no alloc or init required as you are not creating the array yourself. You don't even own this array, so if you are using MRC there is no need to release it later.
NSArray *polygonStringArray = [[NSArray alloc] init];
Now this allocates an immutable empty array and stores a reference to it in polygonStringArray. This is not a very useful array, as it contains nothing and cannot be modified! But you don't keep it around long...
polygonStringArray = [[stringArray objectAtIndex:i] componentsSeparatedByString:#","];
This obtains a reference to an array from componentsSeparatedByString: and stores it in polygonStringArray. If you are using MRC this will cause a leak - your pointless zero-length array created above will leak, and a new zero-length array will be created and leaked every time around the loop.
You are confused over allocation - you only need to allocate things you are creating; when you receive a reference to an already allocated object you only need to store that reference. (If using MRC you may also need to retain/release/autorelease it as well - but let's stick with ARC.) So all you needed here was:
NSArray *polygonStringArray = [[stringArray objectAtIndex:i] componentsSeparatedByString:#","];
Now your code is almost correct, just one typo:
for (int i=0; i < polygonArray.count; i++)
Well you are filling polygonArray in this loop and it starts off as empty, what you need is stringArray.count.
HTH

Sort 2 arrays? Objective-c [duplicate]

I have several arrays that need to be sorted side by side.
For example, the first array has names: #[#"Joe", #"Anna", #"Michael", #"Kim"], and
and the other array holds addresses: #[#"Hollywood bld", #"Some street 3", #"That other street", #"country road"], where the arrays' indexes go together. "Joe" lives at "Hollywood bld" and so on.
I would like to sort the names array alphabetically, and then have the address array sorted alongside so they still go together, with "Hollywood bld" having same index as "Joe". I know how to sort one array alphabetical with
NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:#"name" ascending:NO];
[myArray sortUsingDescriptors:[NSArray arrayWithObject:sort]];
But is there any easy way of getting the second array sorted using the appropriate order?
Create a permutation array, initially set to p[i]=i
Sort the permutation according to the name key of the first array
Use the permutation to re-order both arrays
Example: let's say the first array is {"quick", "brown", "fox"}. The permutation starts as {0, 1, 2}, and becomes {1, 2, 0} after the sort. Now you can go through the permutation array, and re-order the original array and the second array as needed.
NSArray *first = [NSArray arrayWithObjects: #"quick", #"brown", #"fox", #"jumps", nil];
NSArray *second = [NSArray arrayWithObjects: #"jack", #"loves", #"my", #"sphinx", nil];
NSMutableArray *p = [NSMutableArray arrayWithCapacity:first.count];
for (NSUInteger i = 0 ; i != first.count ; i++) {
[p addObject:[NSNumber numberWithInteger:i]];
}
[p sortWithOptions:0 usingComparator:^NSComparisonResult(id obj1, id obj2) {
// Modify this to use [first objectAtIndex:[obj1 intValue]].name property
NSString *lhs = [first objectAtIndex:[obj1 intValue]];
// Same goes for the next line: use the name
NSString *rhs = [first objectAtIndex:[obj2 intValue]];
return [lhs compare:rhs];
}];
NSMutableArray *sortedFirst = [NSMutableArray arrayWithCapacity:first.count];
NSMutableArray *sortedSecond = [NSMutableArray arrayWithCapacity:first.count];
[p enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSUInteger pos = [obj intValue];
[sortedFirst addObject:[first objectAtIndex:pos]];
[sortedSecond addObject:[second objectAtIndex:pos]];
}];
NSLog(#"%#", sortedFirst);
NSLog(#"%#", sortedSecond);
First off, you might want to re-consider an architecture that requires you to sort two arrays in a parallel fashion like this. But having said that, you can do it by creating a temporary array of dictionaries that keep the elements of the two arrays paired.
Then you sort the combined array, and extract the two arrays again, sorted as requested:
Original data:
NSArray *names = #[#"Joe", #"Anna", #"Michael"];
NSArray *addresses = #[#"Hollywood bld", #"Some street 3", #"That other street"];
The actual sorting code:
NSMutableArray *combined = [NSMutableArray array];
for (NSUInteger i = 0; i < names.count; i++) {
[combined addObject: #{#"name" : names[i], #"address": addresses[i]}];
}
[combined sortUsingDescriptors:#[[NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES]]];
names = [combined valueForKey:#"name"];
addresses = [combined valueForKey:#"address"];
Notice that valueForKey: used on an array extracts a new array with the same size, populated with the properties of the objects in the original array. In this case, it create new arrays from the original ones, sorted as wanted.
This approach only requires a few lines of code and is easy to follow and debug, if needed.
The best way is to restructure your data so that you only have one array. In your example, it would make most sense to create a new class with both name and address, put those in an array and sort it by name.
You could probably do this by keeping track of indexes of objects before and after the sort but maybe it would be easier having a single object which hass all of these properties
Person : NSObject
#property (nonatomic, copy) NSString *name;
#property (nonatomic, copy) NSString *addresss;
Then you store these objects into a single array which you can sort by name, or address key paths

add array to array in array - objC

Man,just like the topic above if i want to make change directly with an exiting mutable array.
i want to know how to add a new array to an exiting array in a mutable array
Thanks for any advise!
The problem which you mentioned to add an array into another array which is contained in the NSMutableArray, it can be done like
NSMutableArray *childArray = [self.ParentArray objectAtIndex:index];
[childArray addObjectsFromArray:yourArrayToAdd];
hope that will solve your problem
Suppose we have an NSMutableArray named numbersArray
numbersArray = [[NSMutableArray alloc]initWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",#"7",#"8",#"9",#"10" , nil];
if you want to add an array to it instead of the original, lets say that array is an random array of its own content:
NSMutableArray *temp = [[NSMutableArray alloc] initWithArray:numbersArray];
for(NSUInteger i = [numbersArray count]; i > 1; i--) {
NSUInteger j = arc4random_uniform(i);
[temp exchangeObjectAtIndex:i-1 withObjectAtIndex:j];
}
numbersArray = temp;
the last line give the numbersArray the content of the temp array
and we can do that with
numbersArray = [temp copy];
for the index exchange you can use exchangeObjectAtIndex as follow:
[numbersArray exchangeObjectAtIndex:0 withObjectAtIndex:3];
[numbersArray exchangeObjectAtIndex:1 withObjectAtIndex:4];
[numbersArray exchangeObjectAtIndex:2 withObjectAtIndex:5];

How to change the values of an NSString inside an NSMutableArray?

I have a mutable array of strings. For this example, let's say there are 2 strings in it.
The operation that I would like to do is take the first string and assign the value of the second string to it.
I was trying something like this:
- (void) someAction {
NSMutableArray * array = [[NSMutableArray alloc] initWithObjects: string1, string2, nil];
NSString * firstString = [array objectAtIndex:0];
NSString * secondString = [array objectAtIndex:1];
firstString = secondString;
}
But this method doesn't seem to work. As after I log these two strings, they don't change after the operation.
Please advise.
You can't change strings in an array like that.
The array contains pointers to the strings, and when you assign one string to another you are just swapping pointers around, not changing the string object that the array points to.
What you need to do to swap the string in the array is this:
- (void) someAction {
NSMutableArray * array = [[NSMutableArray alloc] initWithObjects: string1, string2, nil];
NSString * secondString = [array objectAtIndex:1];
[array replaceObjectAtIndex:0 withObject:secondString]; //replace first string with second string in the array
}

How to assign integer from NSMutableArray

I would like to assign NSInteger by using NSMutableArray is there any way to solve this?
It is not working on simulator and cut off when run the application.
NSInteger Section;
NSMutableArray dataSourceSection;
Section = (NSInteger)[dataSourceSection objectAtIndex:2];
Thank you.
A NSMutableArray only stores objects. NSInteger is not an object, but a primitive data type. There is a class NSNumber, however, that can be used instead to store numeric values inside objects. Here's one example.
NSNumber *five = [NSNumber numberWithInteger:5];
NSMutableArray *numbers = [NSMutableArray array];
[numbers addObject:five];
To get the object back and retrieve the integer value use,
NSNumber *firstNumber = [numbers objectAtIndex:0];
NSInteger valueOfFirstNumber = [firstNumber integerValue];
you can't pull an NSInteger out of an NSMutableArray, basically because you can't put anything rather than objects in. in your case NSNumber would be the way to put numbers in NSMutablearray. if you do so you can easily get hold of your object, which is an NSNumber, and convert it to a NSInteger by:
NSMutableArray *array = [[NSMutableArray alloc] init];
// populate the array with NSNumbers
NSInteger number = [[array objectAtIndex:2] intValue];