Objective-C memory management: Inside the `setMyArray` method, is it necessary to release `myArray` before setting a new value to it? - objective-c

The following code is on Apple's website.
1) Inside the setMyArray method, is it necessary to release myArray before setting a new value to it? I thought setting the value of an object to a new object, will release the old object from memory.
2) Why does it say myArray = [newArray mutableCopy];, instead of simply saying myArray = newArray;? Is it necessary to pass a mutable copy to our property?
#interface MyClass : NSObject {
NSMutableArray *myArray;
}
#property (nonatomic, copy) NSMutableArray *myArray;
#end
#implementation MyClass
#synthesize myArray;
- (void)setMyArray:(NSMutableArray *)newArray {
if (myArray != newArray) {
[myArray release];
myArray = [newArray mutableCopy];
}
}
#end
EDIT:
Would it be the same if myArray was (nonatomic, retain)
Apple Documentation
copy
Specifies that a copy of the object should be used for assignment. (The default is assign.)
**The previous value is sent a release message**.

With respect to #1, yes you must release myArray before setting a new value to it, otherwise you'll leak. Note the property, it's labelled as a copy, meaning that myArray will hold an object with a reference count of one once its set.
And with regards to #2, because if you don't mutableCopy, you're not getting a copy of the object, you're simply pointing at the other thing. So, if the other thing goes away, you'll have a pointer to a dangling object. Bad things ensue from that point forward.

1 - In order to avoid a memory leak you must release the array before setting a new value to it.
2 - mutableCopy is required in the context you provided in order to geta copy of the object, and not just a pointer. If the original array goes away, you'd be left with a dirty pointer.
FYI, copies in Objective-C are shallow, not deep copies. This means that when you do [array copy] or [array mutableCopy], you get an array which is separate from the original array, but which still points to all the same objects. If you want to perform a deeper copy, you'll have to do it manually, for example by iterating through the original array, making copies of the contents, and adding those copies to a new array.

Related

Items disappearing from array within array

I create a NSMutableArray that I need as long as my app lives, lets call it suseranArray, just after the #implementation of my main class. This Array will hold several objects of a class called Vassal. A Vassal is simply:
1) A NSMutableString
2) Another NSMutableString
3) A NSMutableArray
4) Another NSMutable Array
Each Vassal created is also needed for the life of the app, and they never change.
These objects are made as (retain) properties in an .h file, synthesized in the .m file, and each given an alloc+init whenever the object Vassal is created during the init function. Each vassal has data filled in and stored in the suzerain Array. the 3rd item always has several elements, and after a bug appeared, I put a line to check if it is ever empty, but it never is, and life is good.
Now, later on when a certain Vassal object is needed, we try to access its 3rd property to fetch the data in there, and sometimes that array empty... I checked to see if it disappeared somehow, but it is always there on the debug, carrying a nice address like 0x2319f8a0 which makes sense since the NSMutableString just above it is at address 0x2319fb40 - (I was expecting 00000000 after a lot of headache). What is happening? I my head, I am creating an RETAINed objects, which retains data put in by default, and that object is put inside another, but somehow the data inside the array vanishes. What possible scenario could lead to this? Thank you for your time :)
Note: the last array currently just holds one item at this stage of development, and curiously enough, that one item is never missing, despite the two arrays being 'brothers'
Vassal.h
#interface Vassal : NSObject
#property (retain) NSMutableString *wordBody;
#property (retain) NSMutableString *wordCode;
#property (retain) NSMutableArray *wordRelations;
#property (retain) NSMutableArray *wordLinks;
#end
Vassal.m
#implementation Vassal:NSObject
#synthesize wordBody;
#synthesize wordCode;
#synthesize wordRelations;
#synthesize wordLinks;
-(NSObject*) init
{
if(self=[super init])
{
wordBody=[[NSMutableString alloc] init];
wordCode=[[NSMutableString alloc] init];
wordRelations=[[NSMutableArray alloc] init];
wordLinks=[[NSMutableArray alloc] init];
}
return self;
}
//Somewhere in Suseran:
-(void)fillStuff
{
...
Vassal *vassal=[Vassal new];
for (int i=0;i<[originalDataString length];i++)
{
...
[vassal.wordRelations addObject:anItem];
...
}
int errorTest=[vassal.wordRelations count];
if (errorTest==0)
{
//breakpoint here. Program NEVER comes here
}
[bigArrayOfVassals addObject:vassal];
}
//these arrays are never touched again but here:
-(void) getVassalstuff:(NSMutableString*)codeOfDesiredVassal
{
Vassal *aVassal;
for (int i=0;i<[bigArrayOfVassals count];i++)
{
aVassal=bigArrayOfVassals[i];
if ([codeOfDesiredVassal isEqualToString:aVassal.wordCode)
{
int errorTest=[aVassal.wordRelations count];
if (errorTest==0)
{
//yay! this breakpoint sometimes is hit, sometimes not,
//depending on code's mood. Why is this happening to me? :,(
}
}
}
}
I see that that you have properties that are mutable (which is itself a bad idea except for specific cases) and that you are retaining them.
Mutability means that if you have set the array as a property based on some other array, and if that original array is changed, the array in your property is also changed. It may be, and I don't know because you haven't shown any code, that you are emptying the original array, and thus changing the array you have as a property
Solutions:
My preferred solution is to use the immutable versions of these classes for your properties; NSString, NSArray and instead of retain use copy
A second solution is to leave the properties as mutable, but write a custom setter for each of them that stores a mutableCopy of the object that you pass in.
In both of these cases, your property will be a copy of the object used to set the property, so that if the object is changed outside of your class it will not affect your class's properties.
edited to add, after a comment
If you declare your property as
#property (copy) NSArray wordRelations;
Then simply writing
vassal wordArray = tempArray;
will do the same thing and is cleaner and more readable..

what does it mean to declare a NSNumber variable as property copy

I am still learning ..., so for the following property
#property (copy) NSNumber *foo;
What the copy really do? make a copy of the (value of) foo and put it to new place? Just like a copy constructor?
And also to clarify, the following is basically doing a AddRef, right?
#property (retain) NSNumber *foo;
See the description of properties here:
http://cocoacast.com/?q=node/103
copy means that assigning a value into the property will make a copy of the input value.
retain means that you won't get an actual copy; you'll get the same object with an extra retain on it. So if it's modified elsewhere, you'll see the modifications in both places.
For NSNumbers, they are immutable, so copy and retain are functionally equivalent.
What the copy really do?
In general, NSNumber is immutable -- I'd expect that copy in those cases would be implemented using retain:
- (id)copyWithZone:(NSZone*)zone {
return [self retain];
}
And also to clarify, the following is basically doing a AddRef, right?
Well, synthesizing it will add the reference counting boilerplate - the actual operation is more complex and takes the generalized form:
- (void)setFoo:(NSNumber *)arg {
NSNumber * prev = foo;
foo = [arg retain]; // << or foo = [arg copy]; if you have specified 'copy'
[prev release];
}

What is the rule of thumb for using #property(copy) vs. #property(retain)?

I wonder if there is a rule of thumb you follow, when deciding whether or not a given property in ObjectiveC should be a retain or copy?
How do you decide which it should be?
Typically you use copy for safety with classes which have mutable variants, like NSString, NSArray, the other collection classes, etc. To see why, consider what happens here...
Once upon a time,
#interface MyClass : NSObject
#property (retain) NSString *happyString;
- (void)rejoice;
#end
Then one day,
- (void)bigBadMethod {
MyClass *myObject = [[[MyClass alloc] init] autorelease];
NSMutableString *theString = [NSMutableString stringWithString:#"I'm happy!"];
myObject.happyString = theString; // this is allowed because NSMutableString inherits from NSString
[myObject rejoice]; // prints "I'm happy!"
when suddenly...
[theString setString:#"BRAAAAIIINNNSSSSS"];
[myObject rejoice]; // prints "BRAAAAIIINNNSSSSS"
}
And you wouldn't want that, would you? So use #property (copy) if you don't want to get mutated while you're not looking!
In a nutshell, assign vs retain vs copy determines how the synthesized accessors interact with the Objective-C memory management scheme:
assign is the default and simply performs a variable assignment
retain specifies the new value should be sent -retain on assignment and the old value sent release
copy specifies the new value should be sent -copy on assignment and the old value sent release.
Remember that retain is done on the created object (it increases the reference count) whereas copy creates a new object. The difference, then, is whether you want to add another retain to the object or create an entirely new object.

What happens to a property if its value is overwritten?

Lets suppose I created a property tempStr that is of NSString type.
I synthesized it obviously.
In one of my methods, I set the value of tempstr to be yellowcolor.
Then just after that I reinitialized tempStr with redcolor.
So I wanna know what happens to the memory of tempStr in this case.
Thanx.
It depends on what attribute you set for your property: retain, assign or copy.
#property (retain) NSString *tempStr: the old value (yellowcolor) would be released and the new value (redcolor) would be retained. The only exception is when yellowcolor == redcolor. Then nothing would happen, because old and new values are the same.
#property (assign) NSString *tempStr: there would be no release/retain operations. It is equal to changing just a pointer. So after this operations yellowcolor won't be released and you'll lost a reference to it (if there is no other reference to it in your code). So it can cause a memory leak.
#property (copy) NSString *tempStr: it's similar to retain but it call copy on new value instead of just retain, so it'd create a duplicate object in a memory. Considering NSString, it's equal to retain, because NSString is immutable, so there is no need to make a duplicate.
You can find some code examples here.
EDIT: As #Bavarious mentioned, copy is equal to retain only if you initialize this property with NSString. It won't be equal if you initialize it with NSMutableString, because this one is mutable, so the "proper" copy would be make.
A synthesized setter looks a bit like this:
- (void)setSomeString:(NSString *)newString
{
if ([newString isEqualToString:someString]) return;
[someString autorelease];
someString = [newString copy]; // or [newString retain], depends how you defined the property ...
}
So the old value is released when the new value is assigned to the pointer.

objective-c "mutating method sent to immutable object" error

I'm pretty new to objective-c and try to create a small app for the iphone.
I'm nearly done beside this little error here. Actually, I've searched hours with google to find a proper solution but unfortunately I'm not able to find a solution which works.
I'm using this tutorial here to build up an UITableView: UITableView Tutorial
The full error message looks like this:
* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '* -[NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'
This is the Data Controller Header:
MyLinksDataController.h
#interface MyLinksDataController : NSObject {
NSMutableArray *tableList; //<---important part
}
- (unsigned)countOfList;
- (id)objectInListAtIndex:(unsigned)theIndex;
- (void)addData:(NSString *)data; //<---important part
- (void)removeDataAtIndex:(unsigned)theIndex;
#property (nonatomic, copy, readwrite) NSMutableArray *tableList; //<---important part
.....
And the Data Controller Method:
MyLinksDataController.m
#import "MyLinksDataController.h"
#implementation MyLinksDataController
#synthesize tableList;
- (id)init {
if (self = [super init]) {
NSLog(#"Initilizing DataController");
//Instantiate list
NSMutableArray *localList = [[NSMutableArray alloc] init];
self.tableList = [localList copy];
[localList release];
//Add initial Data
[self addData:#"AAAAAAAAAAAAAA"];
[self addData:#"BBBBBBBBBBBBBB"];
}
return self;
}
-------------------------------later on in the source code---------------------------------
- (void)addData:(NSString*)data; {
[tableList addObject:data]; //<---- here the app crashes
}
I would pretty much appreciate any help.
Thank you for your support in advance.
Daniel
Sending the copy message to an NSMutableArray -- as in the following statement in init -- returns an immutable copy.
self.tableList = [localList copy];
Cocoa documentation uses the word immutable to refer to read-only, can't-be-changed-after-initialization objects. Hence the subsequenct call to addObject: fails with an error message.
Note how the assignment statement above doesn't trigger any compiler warning. copy returns an id, which fits comfortably -- as far as the compiler is concerned -- in the NSMutableArray* tableList. There's no runtime error here either, as no messages get passed around; an NSArray pointer is just placed in an NSMutableArray pointer variable.
To obtain a mutable copy, use mutableCopy instead.
Note that both copy and mutableCopy create a new array and copy the content of the original to it. A change in the copy will not be reflected in the original. If you just need another reference to the original array, use retain instead.
You can find more detail in the discussion section of the copyWithZone reference and in the NSMutableCopying protocol reference.
You're running into, basically, the memory management rules of Cocoa (specifically, these details). If there is an object with an immutable version and a mutable version, then sending -copy to an object will return an immutable object.
Let's step through the relevant part.
NSMutableArray *localList = [[NSMutableArray alloc] init];
This creates a new, empty mutable array that you own. Fine.
self.tableList = [localList copy];
This creates an immutable copy of the empty array. Furthermore, you own this freshly created copy. That's two objects you own at the moment.
This also assigns your copied object to the tableList property. Let's look at the property declaration:
#property (nonatomic, copy, readwrite) NSMutableArray *tableList;
This property is declared with the copy attribute, so whenever a new value is assigned to it, another -copy method is sent to it. This third copy, however, is not owned by you—it's owned by the object.
[localList release];
That releases the original empty mutable array. Fine, but there's still the one you made in the second line floating around, unreleased. That's a memory leak.
If you actually need a mutable copy of something, you want the -mutableCopy method. (The documentation for these methods is found under NSCopying and NSMutableCopying.) However, you're never going to get a mutable version of something into a property with the copy attribute, since it will send -copy to whatever it is assigned. Your property should use the retain attribute instead of the copy attribute, and the code to initialize it should look something like this:
NSMutableArray *localList = [[NSMutableArray alloc] init];
self.tableList = localList;
[localList release];
Or, a shorter version:
self.tableList = [NSMutableArray array];
There's no need to copy anything in this situation, you're just creating a fresh object.
If u are assigning localList from another object may be that is not Mutable in that case it can through this kind of error.
I hope it will be helpful.
self.tableList = [localList mutableCopy];
Hi instead of mutableCopy i believe "strong" can also be used to tackle this problem. I had similar problem in my code as well because of using "copy" instead of "strong." So the below line:
#property (copy, nonatomic) NSMutableArray *computers;
It should be:
#property (strong, nonatomic) NSMutableArray *computers;
Hope it will be of immense help for beginners making mistakes like me.
This will resolve the issue:
NSMutableArray *localList = [[NSMutableArray alloc] init];
self.localList = [[NSMutableArray alloc]initWithArray:localList];