Problem with arrays (add and copy) - iphone

I've got a problem. I'm trying to sort the items from 1 array (name: mps) into an other array (name: totalArray), but every item should be in a new array. In short: the items in mps should move into a new array, but every item should be in a new array, so the totalArray is an array of arrays. After that, totalArray should be copied back into mps.
To clarify, here is the code:
NSMutableString *oud = [[NSMutableString alloc] init];
NSMutableString *nieuw = [[NSMutableString alloc] init];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[tempArray removeAllObjects];
NSMutableArray *totalArray = [[NSMutableArray alloc] init];
[totalArray removeAllObjects];
tempArray = [[NSMutableArray alloc] init];
[tempArray removeAllObjects];
for (int j = 0; j < [mps count]; j++)
{
nieuw = [[mps objectAtIndex:j] valueForKey:#"ConfigurationAlias"];
if (j != 0)
{
if ([oud rangeOfString:nieuw].location == NSNotFound)
{
NSLog(#"ADDED!");
[totalArray addObjectsFromArray:tempArray];
[oud setString:nieuw];
[tempArray removeAllObjects];
[tempArray addObject:[mps objectAtIndex:j]];
}
else
{
[tempArray addObject:[mps objectAtIndex:j]];
}
}
else {
[oud setString:nieuw];
[tempArray addObject:[mps objectAtIndex:j]];
}
}
//En de array weer laden in de tabel
//NSLog(#"%#", totalArray);
NSLog(#"%i", [mps count]);
[mps removeAllObjects];
NSLog(#"REMOVED!!!");
NSLog(#"%i", [mps count]);
[mps addObjectsFromArray:totalArray];
NSLog(#"Added totalArray: %i", [totalArray count]);
NSLog(#"%i", [mps count]);
[tempArray release];
[totalArray release];
[tabelView reloadData];
}
Now, here comes my problem:
The log gives the line 2011-04-07 10:02:46.368 Fleet Manager[901:40b] ADDED! 11 times, then it posts 16 (mps count, this is correct), then the line REMOVED!, then 0 (mps count, also correct), but then the line: Added totalArray: 15. This can't be correct, it added 11 times but it counts 15?
This a problem for me, in the first place because it's plain incorrect, but the tableview gets screwed up as well because of the section-amount not being correct either (15 sections). Anybody has any idea what's going on?
EDIT: all the objects in mps are dictionaries, and all of them have a value for the key "ConfigurationAlias".

First, I would like to suggest using debugging mode instead of bunch of NSLog functions to track down what's actually happening inside your objects and variables. Try using breakpoints. Set one for [totalArray addObjectsFromArray:tempArray]; line so every time this line of code is reached the execution would stop and let you look around, check different fields' states inside totalArray and tempArray objects.
Concerning your problem... Since you are using addObjectsFromArray: that means that passed array may pass not one but several objects (thus the plural in method name). I guess one of those "11 times" added more than one element - that should explain the actual count being more than the times you've called this method. Again, please check tempArray contents.
Good luck!

If you want to end up with an array of arrays, you need to be allocating temp arrays inside the loop. It also seems like you are overdoing it with clearing out the arrays.
It appears you are trying to add the value from mps to totalArray regardless of the conditions, so it would make sense to only do that in one place (outside of the conditions).
Also, if you are not mutating the arrays (such as tempArray), you can use NSArray instead, which should be smaller and faster.
Finally, you should be able to assign the new array to mps instead of doing the expensive array copying. Not sure if that is somehow referenced as the table delegate, though.
I would try something like:
NSMutableString *oud = [[NSMutableString alloc] init];
NSMutableString *nieuw = [[NSMutableString alloc] init];
NSMutableArray *tempArray;
NSMutableArray *totalArray = [[NSMutableArray alloc] init];
for (int j = 0; j < [mps count]; j++)
{
tempArray = [[NSMutableArray alloc] init];
[totalArray addObject:tempArray];
[tempArray release];
nieuw = [[mps objectAtIndex:j] valueForKey:#"ConfigurationAlias"];
if (j != 0)
{
if ([oud rangeOfString:nieuw].location == NSNotFound)
{
NSLog(#"ADDED!");
[oud setString:nieuw];
}
}
else {
[oud setString:nieuw];
}
}
NSLog(#"%i", [mps count]);
[mps removeAllObjects];
NSLog(#"REMOVED!!!");
NSLog(#"%i", [mps count]);
[mps addObjectsFromArray:totalArray];
NSLog(#"Added totalArray: %i", [totalArray count]);
NSLog(#"%i", [mps count]);
[totalArray release];
[tabelView reloadData];
}

You should
sort the base array in a tempArray
create an empty resultArray
iterate through tempArray and for each item create an itemArray containing the item on the first position and add this array to resutArray
don't forget to release all alloc-ed temporary data
Check this out for sorting easily: Sorting arrays via Apple

Related

NSMutableArray removeAllObjects replaces contents after removal with other items

sorry if the title is worded oddly, not really sure how to say it. I am adding contents of an array of object's from a JSON into another array, so I can do use a sectioned UITableView. However, when I do the removeAllObjects function call when I've filled enough for the first section, add them to my array, and start to load up the second, it results in the entire first section being replaces by the second section. Is NSMutableArray at fault, or is it something I am not thinking of?
weekScheduleArray = [[NSMutableArray alloc] initWithCapacity:2];
NSMutableArray *temp = [[NSMutableArray alloc] init];
for (int count = 0; count < [jsonObject count]; count++) {
if (count < 7) {
[temp addObject:[jsonObject objectAtIndex:count]];
} else if (count == 7) {
[weekScheduleArray addObject:temp];
[temp removeAllObjects];
[temp addObject:[jsonObject objectAtIndex:count]];
} else {
[temp addObject:[jsonObject objectAtIndex:count]];
}
}
[weekScheduleArray addObject:temp];
Calling [weekScheduleArray addObject: temp] does not add a copy of temp to weekScheduleArray; it adds the array itself. Therefore when you subsequently removeAllObjects from temp then the array in weekScheduleArray is also empty. You can avoid the issue with:
[weekScheduleArray addObject: [temp copy]];
The problem is you are continuing to manipulate the exact same mutable array that you just added to the weekScheduleArray. There's a bunch of ways to solve this. You could create a copy when you add it to weekScheduleArray:
[weekScheduleArray addObject:[temp copy]];
Or you could do this:
[weekScheduleArray addObject:temp];
[temp release];
temp = [[NSMutableArray alloc] init];
[temp addObject:[jsonObject objectAtIndex:count]];
And then when you are done your for loop, remember to release temp.

iphone: addObjectsFromArray not adding after reinitializing nsmutable array

i have the following code
inAppKeys = [[MKStoreManager sharedManager] purchasableObjectsDescription ];
NSMutableArray * unremovableArray = [[NSMutableArray alloc] init];
for(int i = 0; i<[inAppKeys count]; i++){
for (int j=0; j< [categories count]; j++) {
NSString * inAppKey = [[categories objectAtIndex:j] valueForKey:#"inAppKey"];
if([inAppKey isEqualToString: [inAppKeys objectAtIndex:i]]){
[unremovableArray addObject:[categories objectAtIndex:j]];
}
}
}
categories = [[NSMutableArray alloc] init];
[categories addObjectsFromArray:unremovableArray];
where categories is nsmutablearray .. the thing is addObjectsFromArray leave the categories empty .. what do i do wrong?
Looks to me like you're referring to [categories count] and [categories objectAtIndex:j] before you even alloc/init categories.
Having re-read your title ("reinitializing") which suggests you've previously inited categories, I'm now assuming that you have a master set of categories that you're trying to reduce to the ones actually purchased. If so, I wouldn't re-use the variable "categories" as that's confusing. (I assume categories was auto-released, or else you've got a leak). How 'bout using unremovableArray instead of leaking it?
I'd also use fast enumerators for clarity and speed...
NSLog(#"categories: %#", categories);
inAppKeys = [[MKStoreManager sharedManager] purchasableObjectsDescription ];
NSLog(#"inAppKeys:%#", inAppKeys);
NSMutableArray * unremovableCategories = [[NSMutableArray alloc] init];
for(NSString* thisAppKey in inAppKeys) {
for (NSDictionary* thisCategory in categories) {
if ([[thisCategory valueForKey:#"inAppKey"] isEqualToString: thisAppKey]){
[unremovableCategories addObject:thisCategory];
break; //having added this category; no reason to continue looking at it
}
}
}
//now use unremovableCategories...

how do I create fresh NSMutableArray?

I have an NSMutableArray which only lasts during the session.
Currently I create it like this
NSMutableArray *temp = [[NSMutableArray alloc] initWithCapacity:10];
[self setScoreArray:temp];
[temp release];
Problem is when I go to check each index I'm getting an array outofbounds error
NSNumber *previousScore = [[self scoreArray] objectAtIndex:[self quizNum]];
if ( previousScore != nil )
{
[self clearQuizBtns];
NSInteger previousScoreValue = [previousScore integerValue];
[self selectButtonAtTag:previousScoreValue];
}else {
[self clearQuizBtns];
}
I've read in other posts that initWithCapacity doesn't actually create the array. So what can I populate the array with initially?
Thanks in advance.
Two ways:
first: to initiate array with default values of NSNull class
NSMutableArray *temp = [[NSMutableArray alloc] initWithCapacity:10];
for (int i = 0 ; i < 10 ; i++)
{
[temp insertObject:[NSNull null] atIndex:i];
}
[self setScoreArray:temp];
[temp release];
and then to check: if object is kind of NSNull class means it was a never set before
id previousScore = [[self scoreArray] objectAtIndex:[self quizNum]];
if (![previousScore isKindOfClass:[NSNull class]])
{
[self clearQuizBtns];
NSInteger previousScoreValue = [(NSNumber *)previousScore integerValue];
[self selectButtonAtTag:previousScoreValue];
}else {
[self clearQuizBtns];
}
second: store scores in NSMutableDictionary and use NSNumber's as keys
// scoreDictionary property of NSMutableDictionary class must be declared in self
NSNumber *previousScore = [self.scoreDictionary objectForKey:[NSNumber numberWithInt:[self quizNum]]];
if (previousScore != nil)
{
[self clearQuizBtns];
NSInteger previousScoreValue = [previousScore integerValue];
[self selectButtonAtTag:previousScoreValue];
}else {
[self clearQuizBtns];
}
NSArray does not support "holes". The capacity is just a hint to the initializer.
You could either fill the array with placeholder objects or, more typically, change your algorithm to either fully prepopulate the array or to lazy load it linearly.
Your problem seems to be that you're never actually setting any score in the score array.. are you? NSArrays have an actual count of items in them, and accessing an index beyond that count will blow up, as you've seen. If there will only ever be a fixed (small) number of scores, like 10, then you could set them all initially to something default like:
for (int i = 0; i < 10; i++) {
[temp addObject:[NSNumber numberWithInt:0]];
}
P.S. -initWithCapacity does "create the array", it just doesn't create any objects in the array. The capacity is a hint only.
Using the arrayWithObject: or arrayWithObjects: methods can provide an array with pre-populated values.
One cool thing about NSMutableArrays is that you can just do an "init" and the array will handle adding and removing objects on the fly. Remember that you generally addObject: or removeObjectAtIndex: when dealing with mutable arrays.

Problem adding custom objects to Mutable Array

quick question regarding Array's in xcode. I have ht efollowing code, which is supposed to go through an array of strings which it has got through php and JSON, and trun these strings into a custom object with the strings as the ivars for the object then add that object to a new array:
for (int i = 0; i<[list count]; i++) {
Article *article = [[Article alloc] init]; //creates custom object
article.uid = [[list objectAtIndex:i] objectAtIndex:0];
article.title = [[list objectAtIndex:i] objectAtIndex:1]; //adds string as ivars
article.description = [[list objectAtIndex:i] objectAtIndex:2];
articleArray = [[NSMutableArray alloc] init]; //inits the new array
[articleArray addObject:article]; //should add the object but seems to fail
[article release]; //releases the object
NSLog(#"%#", article.description);
}
NSLog(#"%d", [articleArray count]);
NSLog([articleArray description]);
}
The code does return the correct values using NSLog(#"%#", article.description); but not the correct length for the new array and it only adds one value to the array which is the string for article.description which makes no sense to me. The list array contains 2 elements each of which are arrays in themselves containing the strings.
You're recreating the articleArray in every loop. Declarate it outside, and it will work:
NSMutableArray *articleArray = [[NSMutableArray alloc] init]; //inits the new array
for (int i = 0; i<[list count]; i++) {
Article *article = [[Article alloc] init]; //creates custom object
article.uid = [[list objectAtIndex:i] objectAtIndex:0];
article.title = [[list objectAtIndex:i] objectAtIndex:1]; //adds string as ivars
article.description = [[list objectAtIndex:i] objectAtIndex:2];
[articleArray addObject:article]; //should add the object but seems to fail
[article release]; //releases the object
NSLog(#"%#", article.description);
}
NSLog(#"%d", [articleArray count]);
NSLog([articleArray description]);
}
You also may want to use the nicer for(NSArray *listElement in list) syntax instead.

NSArray to NSMutableArray as random stack

Just a conceptual description first:
I am reading input from a text file (a list of words) and putting these words into an NSArray using componentsSeparatedByString method. This works.
But I wanted to select the words randomly and then delete them from the array so as to ensure a different word each time. Of course, you cannot change the NSArray contents. So...
I copied the contents of the NSArray into an NSMutableArray and use IT for the selection source. This also works - 269 objects in each array.
To return a word from the NSMutableArray I use the following code:
note- the arrays are declared globally
as
arrMutTextWords = [[NSMutableArray alloc] init]; //stack for words
arrTextWords = [[NSArray alloc] init]; //permanent store for words
-(NSString*) getaTextWord
{
// if the mutable text word array is empty refill
if ([arrMutTextWords count] == 0){
for (int i = 0 ; i < [arrTextWords count]; i++)
[arrMutTextWords addObject:[arrTextWords objectAtIndex:i]];
}
int i = random() % [arrMutTextWords count];
NSString* ptrWord = [arrMutTextWords objectAtIndex:i];
[arrMutTextWords removeObjectAtIndex:i];
return ptrWord;
}
The program crashes during a call to the method above - here is the calling code:
arrTmp is declared globally arrTmp = [[NSArray alloc] init]; //tmp store for words
for (int i = 0 ; i < 4; i++) {
tmpWord = [self getaTextWord];
[arrTmp addObject:tmpWord];
[arrTmp addObject:tmpWord];
}
I'm thinking that somehow deleting strings from arrMutTextWords is invalidating the NSArray - but I can't think how this would occur.
One possible source for problems is your fetching AND removing the NSString object from your list. Removing it releases that NSString instance therefore devalidating your reference.
To be shure to retain a reference you should use this code sequence instead:
NSString * ptrWord = [[[arrMutTextWords objectAtIndex:i] retain] autorelease];
[arrMutTextWords removeObjectAtIndex:i];
return ptrWord;
By the way: You should use
NSMutableArray *mutableArray = [NSMutableArray arrayWithArray: array];
instead of copying all values by hand. While i do not know the implementation of NSMutableArray, i know from times long ago (NeXTstep), that there are several possible optimizations that may speed up basic NSArray operations.
And finally copying this way is much more concise.
Just ran this through XCode and got random words returned, however I skipped the whole for loop and used addObjectsFromArrayfrom NSMutableArray.
NSArray *randomArray = [[NSArray alloc] initWithObjects:#"Paul", #"George", #"John", nil];
NSMutableArray *muteArray = [[NSMutableArray alloc] init];
[muteArray addObjectsFromArray:randomArray];
int i = random() % [muteArray count];
NSString* ptrWord = [muteArray objectAtIndex:i];
[muteArray removeObjectAtIndex:i];
NSLog(#"ptrWord %#", ptrWord); //gave me a different name each time I ran the function.
Hope this clears some things up.