NSMutableArray replacing object insted of adding - ios

I'm using a NSMutableArray to store an object called poligonon. This object has a NSMutableArray as property to store coordinates X.
But when I add the second object, the first object on the array transform itself. All objects on the array must be differents, but they are equal the last object in the array.
Exemple:
coordArrayX is a property (NSMutableArray)
-saveDataIntoArray
{
poligonon.coorArrayX = coordArrayX;
arrayPoligonon addObject: poligonon;
}
The first time that the user clicks to save, the first coordinate is 74.
Now, he creates a new poligonon that has coordinate 45, and add to the array.
When the user checks, the first poligonon has coordinate = 45.
How to solve?

Each and every time you are adding the same poligonon to the array and overwriting the value of coorArrayX.
Instead of,
{
poligonon.coorArrayX = coordArrayX;
arrayPoligonon addObject: poligonon;
}
Try this,
{
poligonon = [[Poligonon alloc] init];
poligonon.coorArrayX = coordArrayX;
[arrayPoligonon addObject:poligonon];
}

Related

add new object to nsmutablearray replace all objects in array

i try to add new object to my nsmutablearray but every time it replace all object
-(void)addToStack:(Coordinate *)coord{
Coordinate*c = [[Coordinate alloc] init];
c.x=coord.x;
c.y = coord.y;
if (coord.x==0 && coord.y==0) {
c.x=coord.x+1;
[_stack addObject:c];
c.x=coord.x;
c.y=coord.y+1;
[_stack addObject:c];
c.y=coord.y;
}
}
You are not adding a new object but you are changing the old object where the reference will remain the same.
NSMutableArray addObject will not add it because it already exists in the array.
So, when trying to add a new object, first create a copy of the one that you want to change, like this:
Coordinate *newCoordinate = [Coordinate mutableCopy];
// change attributes
// add it to the array
Everybody who said that adding the same object twice deletes the first instance and replaces it, is wrong.
Arrays can contain duplicate references to the same object. However, it's more like saving the same street address in an rolodex twice. If you look up the address in the first entry, go break all the windows in that house, then go back, look up the address in the second slot in your rolodex, and drive to THAT address, you'll find the house has broken windows (Because both addresses point to the same house.)
Similarly, when you add the same object to an array twice, it's two pointers to the same object. When you change values of the object at index 0, you see those changes reflected in the object in index 1 because it's a second pointer to the same object.
Despite saying the wrong thing about what goes wrong with your code, #Shashi3456643 gave you the correct solution, which is to create a new, unique object for every entry in your array.
Make sure to initiate the array:
NSMutableArray *stack=[[NSMutableArray alloc] init];
This is because every time you init the array. Initialize the array once.
For example:
in .h
Coordinate*c;
in .m
- (void)viewDidLoad
{
c = [[Coordinate alloc] init];
}
-(void)addToStack:(Coordinate *)coord{
c.x=coord.x;
c.y = coord.y;
if (coord.x==0 && coord.y==0) {
c.x=coord.x+1;
[_stack addObject:c];
c.x=coord.x;
c.y=coord.y+1;
[_stack addObject:c];
c.y=coord.y;
}
}

NSMutable dictionary not working properly

I am developing an iPad application and for this application I have one function as below :-
-(void)testcurrentest:(NSMutableDictionary *)keydictionary{
NSArray *allKeys = [keydictionary allKeys];
if ([allKeys count] > 0) {
for(int i = 0;i< allKeys.count;i++){
[_currenies removeAllObjects];
NSString *product = [NSString stringWithFormat:#"%#", [keydictionary objectForKey:allKeys[i]]];
int kl = [productPriceSeasonCode intValue];
for(int i =0;i<kl;i++){
[_currenies addObject:#"0"];
}
NSLog(#"................%#",_currenies);
[_currencydictionary1 setObject:_currenies forKey:allKeys[i]];
NSLog(#"full dictionary...%#",_currencydictionary1);
}
}
}
Here, NSLog print the currencies array based on the kl integer values but when I'm trying to set the NSMutableDictionary the currencies but mutable array always show the latest array values.
You are using the same array for all values, they should be unique objects if you don't want change of one value to affect the other values. Initialise _currenies on every loop step or use its deep copy when preparing a new object.
A bit of code:
[_currenies removeAllObjects]; // < The same array you've added to dict on previous loop steps
Creating a new array at each loop step would create a unique object for all key-value pair:
_currenies = [NSMutableArray array]; // < Note it is not retained, apply memory management depending on your project configuration
Your code is a garbled mess. As others have pointed out, you are using the same loop index, i, in 2 nested loops, making it very hard to tell your intent. Don't do that, ever. It's horrible programming style.
You are also creating a string "product" that you never use, and fetching the same integer value of productPriceSeasonCode on every pass through the outer loop. I suspect you meant to fetch a value that varies with each entry in your keydictionary.
Then, you have an array, _currenies, which you empty on each pass through your outer loop. You then add a number of "0" strings to it, set a key/value pair in your _currencydictionary1 dictionary to the contents of that array, and then repeat. Since you re-use your _currenies array each time, every key/value pair you create in your _currencydictionary1 dictionary points to the exact same array, which you keep changing. At the last iteration of your outer loop, all the entries in your _currencydictionary1 will point to your _currenies array, which will contain the last set of contents you put there.
Create a new array for each pass through your outer array, and add that newly created array to your _currencydictionary1. You want a unique array in each key/value pair of your _currencydictionary1.
In short, NSMutableDictionary is working just fine. It's your code that isn't working properly.
Not an answer but comments don't have formatting.
The question should provide more information on the input and desired output.
First simplify your code and it should be easier to find the error:
-(void)testcurrentest:(NSMutableDictionary *)keydictionary{
NSArray *allKeys = [keydictionary allKeys];
for(NSString *key in allKeys) {
[_currenies removeAllObjects];
int kl = [productPriceSeasonCode intValue];
for(int i =0; i<kl; i++){
[_currenies addObject:#"0"];
}
NSLog(#"................%#",_currenies);
_currencydictionary1[key] = _currenies;
NSLog(#"full dictionary...%#",_currencydictionary1);
}
}
Note: product was never used.

Objective-C how to pull several random items out of NSArray without getting duplicates? [duplicate]

This question already has answers here:
Getting a random object from NSArray without duplication
(3 answers)
Closed 7 years ago.
I have an array of random properties I would like to assign to equipment within the game I'm developing.
The code that I use below is returning an NSArray. I'm interested if there's way to get item indices from that array without getting duplicate values. The obvious solution is to create a mutable array with the returned array, do random, remove item that was returned and loop until the number of items is received.
But is there a different way of getting X random items from NSArray without getting duplicates?
//get possible enchantments
NSPredicate *p = [NSPredicate predicateWithFormat:#"type = %i AND grade >= %i", kEnchantmentArmor,armor.grade];
NSArray* possibleEnchantments = [[EquipmentGenerator allEnchantmentDictionary] objectForKey:#"enchantments"];
//get only applicable enchantments
NSArray *validEnchantments = [possibleEnchantments filteredArrayUsingPredicate:p];
NSMutableArray* mutableArray = [NSMutableArray arrayWithArray:validEnchantments];
NSDictionary* enchantment = nil;
if(mutableArray.count>0)
{
//got enchantments, assign number and intensity based on grade
for (int i = 0; i<3;i++)
{
enchantment = mutableArray[arc4random()%mutableArray.count];
[mutableArray removeObject:enchantment];
//create enchantment from dictionary and assign to item.
}
}
You can shuffle the array using one of the following techniques:
What's the Best Way to Shuffle an NSMutableArray?
Non repeating random numbers
Then, take the first X elements from the array.
Many years ago, I was working on card game and I realized that shuffling the deck was an inefficient way to get random cards. What I would do in your shoes is pick a random element, and then replace it with the element at the end of the array, like so:
#interface NSMutableArray (pickAndShrink)
- (id) pullElementFromIndex:(int) index // pass in your random value here
{
id pickedItem = [self elementAtIndex:index];
[self replaceObjectAtIndex:index withObject:[self lastObject]];
[self removeLastObject];
return pickedItem;
}
#end
The array will shrink by one every time you pull an element this way.
You could use a random number generator to pick a starting index, and then pick the subsequent indices based on some kind of math function. You would still need to loop depending on how many properties you want.
Eg:
-(NSMutableArray*)getRandomPropertiesFromArray:(NSArray*)myArray
{
int lengthOfMyArray = myArray.count;
int startingIndex = arc4random()%lengthOfMyArray;
NSMutableArray *finalArray = [[NSMutableArray alloc]init]autorelease];
for(int i=0; i<numberOfPropertiesRequired; i++)
{
int index = [self computeIndex:i usingStartingIndex:startingIndex origninalArray:myArray];
[finalArray addObject:[myArray objectAtIndex:index]];
}
return finalArray;
}
-(int)computeIndex:(int)index usingStartingIndex:(int)startingIndex
{
//You write your custom function here. This is just an example.
//You will have to write some code to make use you don't pick an Index greater than the length of your array.
int computedIndex = startingIndex + index*2;
return startingIndex;
}
EDIT: Even your computeIndex function could use randomness in picking the subsequent indices. Since you have a startingIndex, and another index, you could use that to offset your function so that you never pick a duplicate.
EDIT: If your array is very large, and the subset you need to pick is small, then rather than shuffle the entire array (maybe more expensive), you could use this method to pick the number of items you need. But if your array is small, or if the number of items you need to pick are almost the size of the array, then the godel9's solution is better.
You can use a mutable array and then remove them as the are selected, use something like random()%array.count to get a random index. If you don't want to modify the array then copy it with [array mutableCopy].

Edited UITableViewCell is being stored as a new cell

I have a table view that has a data source in sync with Core Data. However, I'm having a problem. Whenever I edit or delete a tableview cell, and I reload the view, I see a copy of the tableview cell that was there before it was edited. Here's some code to make it clearer.
When the view first loads, it tries to get all the "SOCommands" from "SOModule" which has a one-to-many relationship. Then, it converts it into "SOCommandTemp", so that I can work with them without altering the database.
_serverModuleCommands = [[NSMutableArray alloc]initWithArray:[self.serverModule.socommand allObjects]];
for(int i=0;i<[_serverModuleCommands count];i++)
{
SOCommandTemp* newTemp = [[SOCommandTemp alloc]init];
newTemp.commandName = ((SOCommand*)[_serverModuleCommands objectAtIndex:i]).commandName;
newTemp.sshCommand = ((SOCommand*)[_serverModuleCommands objectAtIndex:i]).sshCommand;
[_serverModuleCommands replaceObjectAtIndex:i withObject:newTemp];
}
Then, when I'm editing cells, I call methods such as these:
[_serverModuleCommands addObject:commandValues]; //commandValues is in the form of SOCommandTemp
[_serverModuleCommands replaceObjectAtIndex:_selectedCommandCell.row withObject:commandValues]; //_selectedCommandCell is an ivar that is cleared immediately after use
Then, when saving, I convert the array into SOCommand by doing this:
for(int j=0; j<[_serverModuleCommands count]; j++){
SOCommand* newCommand = [NSEntityDescription insertNewObjectForEntityForName:#"SOCommand" inManagedObjectContext:self.managedObjectContext];
newCommand.commandName = ((SOCommandTemp*)[_serverModuleCommands objectAtIndex:j]).commandName;
newCommand.sshCommand = ((SOCommandTemp*)[_serverModuleCommands objectAtIndex:j]).sshCommand;
newCommand.somodule = newModule;
}
However, before this is called, I want to make sure that I'm saving only one array item, since I added and editing one cell, so I do this:
NSLog(#"Going to Save: %#",[_serverModuleCommands description]);
And sure enough, I get only 1 array item. Then, I do save it, and exit the view controller. But when the first line:
_serverModuleCommands = [[NSMutableArray alloc]initWithArray:[self.serverModule.socommand allObjects]];
is called again, I'm getting two values in its description, one for the original and one for the edited.
Any help would be great!
~Carpetfizz
In your saving segment, you create a new SOCommand object no matter if it already exist.
Why not just use the actual objects (SOCommand) and edit them, this will not alter your DB information until you save the context.
It will save you some grieve swapping back and forth between your objects.
If you cannot edit in context, you should pass the existing item objectID to your "temp" objects and if it exist, fetch this object from DB and make the update to the existing item:
NSManagedObjectID* oID = ((SOCommandTemp*)[_serverModuleCommands objectAtIndex:j]).objectID;
if(oID) {
SOCommand* cmd = (SOCommand*)[context existingObjectWithID:oID error:nil];
if (cmd) { //no error fetching the object
//update `cmd` with your new values
}
}

Object becomes duplicated in NSMutableArray

Im trying to add an object to NSMutableArray it seems to get duplicated.
#interface TestObject : NSObject {
double a_actual;
double a_target;
}
#property(assign) double a_actual;
#property(assign) double a_target;
Create some pointers:
NSMutableArray * myTestObjectArray;
TestObject * myTestObject;
Init them:
myTestObjectArray = [[NSMutableArray alloc] init];
myTestObject = [[TestObject alloc] init];
I add value to the object and add it to the array:
[myTestObject setA_actual:234];
[myJointDataArray insertObject:myTestObject];
I add different values to each object, but i do not necessarily fill all the variables out.
When i print each object out i have the same (last) value duplicated in all objects for some reason.
Printing the array shows that all objects are the same:
Array: (
"<TestObject: 0x6b9b400>",
"<TestObject: 0x6b9b400>",
"<TestObject: 0x6b9b400>",
"<TestObject: 0x6b9b400>",
"<TestObject: 0x6b9b400>",
"<TestObject: 0x6b9b400>" )
Should i alloc a new object of TestObject everytime i want to work with a new?
Should i alloc a new object of TestObject everytime i want to work with a new?
Yes. If you don't allocate a new object, you're just working with the same object over and over again. It appears you want multiple, distinct objects, so allocate a new instance for each one.
To make it more clear to you why it is failing, consider that insertObject: takes a pointer to an object as a parameter. So when you send the insertObject: message to your array, it will store a pointer to that object, not a copy of the object itself. That's why you have to alloc/init a new instance of it.
You are basically adding the same object. If you check the value of "a_actual" for each object inside your array, you will see it's the same. You should allocate a new one and add it.

Resources