I'm sure I'm doing something silly, but this is driving me crazy.
I'm trying to loop through database results, create objects from those results, and add the objects to an NSMutableArray. I've verified via NSLog calls that the data is being correctly read from the database and copied to the object, but the count for the NSMutableArray always returns 0.
Here's the essence of the code:
while ([rs next]) {
Kana *htemp = [Kana alloc];
htemp.content = [rs stringForColumn:#"hiragana"];
[hiragana addObject:htemp];
}
NSLog(#"Hiragana contains %d objects", [hiragana count]);
Kana is derived from NSObject, and hiragana is an instance of NSMutableArray.
I'm sure this is a rookie mistake, and I hope someone can set me straight. TIA! :)
My guess, judging from the code you posted, is that you probably aren't allocating your array properly. When creating objects, you need to initialize them as well. Therefore, this:
Kana *htemp = [Kana alloc];
Should be:
Kata *temp = [[Kana alloc] init];
All objects need to be initialized this way. Thus, if I'm correct and you haven't initialized your array, then your creation needs to go from this:
NSMutableArray *hiragana = [NSMutableArray alloc];
to this:
NSMutableArray *hiragana = [[NSMutableArray alloc] init];
For optimization reasons, you should probably also specify an initial capacity as well if you have any idea how many objects you might hold:
[[NSMutableArray alloc] initWithCapacity:someNumber];
Another common cause (not in your case, as it turns out, but generally) is forgetting to even allocate the array. If you haven't created an array yet, you're sending that count message to nil, so the result will always be 0.
A few things:
What happens if you put an NSLog call inside of the while loop? Verify that loop iterations are actually happening before blaming it on the array.
Where are you creating the array hiragana? If you are doing it incorrectly for some reason and the array is nil, it might cause problems like this.
If you do not have garbage collection on, be sure to do [htemp release] after adding it to the loop. addObject retains and each added item will leak from the loop. Again, this is only relevant if garbage collection is off.
It's most likely either you aren't created the array correctly or rs doesn't contain what you expect it to contain, and so [rs next] isn't getting called ever (if rs is nil, for example, no iterations of this loop would execute and you wouldn't have any sort of error).
Related
I have noticed, that even that my code is working great, something strange happen.
Assume I have two arrays: passwordEntered and tempPasswordEntered.
After I get a new passwordEntered, I do this each time:
tempPasswordEntered=[passwordEntered mutableCopy];
Then I clean :
[passwordEntered removeAllObjects];
then, next time I again do this (for the new passwordEntered):
tempPasswordEntered=[passwordEntered mutableCopy];
So tempPasswordEntered has only the last passwordEntered, and not both of them.
if first time it had 4 places in array,the second time it still has 4 places,
so my question is, does the copy REPLACE the array ? its not added to the last place of it as when you addObject ?
Another thing: should I use retain instead?
The line tempPasswordEntered=[passwordEntered mutableCopy]; is a variable assignment, and like other assignments it changes the value of the variable completely. In this case, tempPasswordEntered now points to a copy of passwordEntered, which has only a single object in it. So yes, it does replace the array, like any other assignment would.
If you wanted to add the objects in passwordEntered to tempPasswordEntered, try [tempPasswordEntered addObjectsFromArray:passwordEntered].
It sounds like what you want is mutableCopy, not retain, but I don't really know what your requirements are exactly so I can't say much more. You should probably be using ARC anyways :)
NSArray *retVal = [[NSArray alloc] initWithArray:fetchResults];
NSArray *retVal = [[NSArray alloc] initWithArray:[fetchResults copy]];
NSArray *retVal = [[NSArray alloc] initWithArray:[fetchResults retain]];
The latter two are simple leaks. The first is one way of making a copy, but retVal = [fetchResults copy]; is a better way to make a copy.
But, of course, you don't need a copy at all. That isn't the problem. You go on to say that the only thing that doesn't crash is an empty result set.
That indicates one of two things; either your result set is corrupt (unlikely) or you are accessing the result set incorrectly (likely).
I was having a problem with my app throwing an exception when calling removeObjectAtIndex on an NSMutableArray, saying that myLocationsArray was declared immutable. All other manipulation on that array was fine, it was most definitely declared correctly etc etc but somewhere in my app it was getting set as immutable. After investigating for a while trying to find where it was getting set immutable, I decided screw it and just redeclared the variable as such:
myLocationsArray = [[NSMutableArray alloc] initWithArray:[defaults
objectForKey:MYLOCATIONSARRAY_KEY]];
right before the removeObjectAtIndex call.
However I know this has got to be badwrong, I'm calling alloc/init twice on the same variable. However it's the only thing that has worked. Is there any way to remind this variable that it is an NSMutableArray without introducing memory leaks like I am?
NSUserDefaults returns immutable copy of your array. It doesn't matter whether you put NSArray or NSMutableArray in it, it always give you immutable copy back.
So, do this to get a mutable copy that you can work with
myLocationsArray = [[NSMutableArray alloc] initWithArray:[[[defaults objectForKey:MYLOCATIONSARRAY_KEY] mutableCopy] autorelease]];
or just this
myLocationsArray = [[defaults objectForKey:MYLOCATIONSARRAY_KEY] mutableCopy];
I would suggest to set a breakpoint on the line where your program is throwing an exception (the one containing removeObjectAtIndex) and inspect with the debugger the real type of the array. If you go with you mouse over the array name, a popup menu will display giving you all the information you need about the pointed object.
What I expect is that you find out this way that the object is an NSArray (vs. NSMutableArray) and then trace back to the point where you initialized it in the first place.
It looks like you're working with NSUserDefaults. All objects you get out of NSUserDefaults are always immutable, regardless of what you stored into it. NSUserDefaults doesn't keep a reference to the specific object you set into it, it keeps the data. It's effectively making a copy. When you get something out of NSUserDefaults, it makes a new (immutable) object from the data it has stored and gives that to you.
Unsurprisingly, you can't change what's stored in NSUserDefaults by mutating what you (think you) stored in it. You can only change what's stored by replacing what you previously stored by storing something anew.
The declaration should not matter; your error is a run-time error. It sounds like your myLocationsArray variable has been assigned an immutable array (NSArray) though whether it is being re-assigned somewhere or was always immutable is impossible to say from your code fragment.
I often see something like:
NSArray *tmpArr = [[NSArray alloc] initWithObjects:#"Info", nil];
self.userInfo = tmpArr;
[tmpArr release];
instead of:
self.userInfo = [[NSArray alloc] initWithObjects:#"Info", nil];
Does anyone know why the top code sample is more popular? Is it more correct memory management than the second?
Second code snippet causes a memory leak due to the array not being released. In most cases properties of object types (like NSArray in this case) are either retain or copy properties and this means they either increase the reference count of the assigned value or copy the whole object. Then the local variable can be (and should be) released if it's not needed anymore.
Non-leaking alternative to the second code snipped would be using autorelease:
self.userInfo = [[[NSArray alloc] initWithObjects:#"Info", nil] autorelease];
or simply:
self.userInfo = [NSArray arrayWithObjects:#"Info", nil];
Assuming that the property userInfo is marked retain, the second form will leak memory. [[NSArray alloc] initWithObjects] will create an array with a reference count of one. Assigning it to a retain property will increase the reference count to two and it will never come back down to zero and be released. It can be fixed either by using the first form you listed or by:
self.userInfo = [[[NSArray alloc] initWithObjects:#"Info", nil] autorelease];
so that the auto release will decrement the reference count to one at the next iteration of the run loop. From then when userInfo is cleared, the reference count will go down to zero and the array will be destroyed.
You should also take a look at this question
Apart from any other reasons there might be, it makes the code more readable and helps to prevent errors.
Your two examples are not equivalent, because you forgot to release the newly alloc/init'ed array in the second one. You would have needed
self.userInfo = [[[NSArray alloc] initWithObjects:#"Info", nil] autorelease];
here.
QED first reason ;-P
Moreover, when you create a local variable first, you can build up more complex objects before publicizing them via a property. If, for example, you were using a mutable array here and filled it with some more complex logic, assigning it to the property right away and only when going on filling it up, clients of your class might access the property with its contents being only half ready – a great provision for sporadic and hard to reproduce bugs.
So even though in your case it would not have been strictly necessary to use a local variable (if you either had autorelease'd it our used the new Automatic Reference Couting "ARC", which would have solved the leak issue automatically), in my opinion it is always a good idea to first get everything ready and then make it visible.
Clean code rules :)
Sorry for the newbie question, but I need a NSMutableArray with some NSNumber inside, created dynamically in a for cycle. My code looks like this:
for (...){
NSNumber *temp_number = [[NSNumber alloc] initWithInteger:someNSInteger];
[target_array addObject:[temp_number copy]];
[temp_number release];
}
Is this a correct way to do it? Does it leak?
Thanks! Miguel
Yep, that leaks. You want:
NSNumber *temp_number = [[NSNumber alloc] initWithInteger:someNSInteger];
[target_array addObject:temp_number];
[temp_number release];
So, no copy. The logic is that because you use alloc, you end up owning temp_number. You then add it to the array and the array does whatever it needs to. You've used temp_number for its intended purpose, so you no longer want to own it and release it.
If you were to take a copy, that would create another instance of NSNumber, which you also own, and therefore which you should also release when you're finished with.
In practice, the array (if it's allocated and exists, rather than being nil), will retain the object for itself, but that's an implementation detail specific to that class and not something you should depend upon or even be particularly interested in beyond the contract that says that the objects you add can later be found in the array.
I'm getting lost in pointer land, I believe. I've got this (code syntax might be a little off, I am not looking at the machine with this code on it...but all the pertinent details are correct):
NSMutableArray *tmp = [[NSMutableArray alloc] init];
I them pass that to a routine in another class
- (BOOL)myRoutine: (NSMutableArray *)inArray
{
// Adds items to the array -- if I break at the end of this function, the inArray variable has a count of 10
}
But when the code comes back into the calling routine, [tmp count] is 0.
I must be missing something very simple and yet very fundamental, but for the life of me I can't see it. Can anyone point out what I'm doing wrong?
EDIT: www.stray-bits.com asked if I have retained a reference to it, and I said "maybe...we tried this: NSMutableArray *tmp = [[[NSMutableArray alloc] init] retain]; not sure if that is what you mean, or if I did it right.
EDIT2: Mike McMaster and Andy -- you guys are probably right, then. I don't have the code here (it's on a colleague's machine and they have left for the day), but to fill the array with values we were doing something along the lines of using a decoder(?) object.
The purpose of this function is to open a file from the iPhone, read that file into an array (it's an array of objects that we saved in a previous run of the program). That "decoder" thing has a method that puts data into the array.
Man, I've totally butchered this. I really hope you all can follow, and thanks for the advice. We'll look more closely at it.
You don't need to call retain in this case. [[NSMutableArray alloc] init] creates the object with a retain count of 1, so it won't get released until you specifically release it.
It would be good to see more of the code. I don't think the error is in the very small amount you've posted so far..
I agree with Mike - based on the code you've posted, it looks correct. In addition to posting the code used to call the function and add items to the array, you could try checking the memory addresses of the pointer at the end of the function (when it has all of the objects), and also once it has returned (when it has no objects). I'm not sure why it would be different, but then again the items should stick in the array as well.
You need to show us a bit more of how you're adding objects to the array for us to really help.
I've seen a lot of people write code like this:
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:0];
array = [foo bar];
People doing this think it "creates and then sets" a mutable array, but that's not at all what it does. Instead, it creates a mutable array, assigns it to the variable named array, and then assigns a different mutable array to that variable.
So be sure you're not confusing the variable for the object to which it is a reference. The object isn't the variable, it's interacted with through the variable.
NSMutableArray retains objects added to it, but have you retained the array itself?
The code you posted should work. You must be doing something funny in the decoder function.
You should not retain that array. It's automatically retained with init. If you retain it, you'll leak memory. If you are just starting with objective c, take time and read "Introduction to Memory Management Programming Guide for Cocoa". It will spare you lots of headache.
Why are you writing so much code to read an array from a file? It's already supported by the framework:
+ arrayWithContentsOfFile:
Returns an array initialized from the contents of a specified file.
The specified file can be a full or
relative pathname; the file that it
names must contain a string
representation of an array, such as
that produced by the
writeToFile:atomically: method.
So you can do this:
NSMuatableArray *myArray = [NSMutableArray arrayWithContentsOfFile:#"path/to/my/file"];
This is a convenience method, so the object will autorelease. Make sure to retain this one if you want to keep it around.