Objective-C classes, pointers to primitive types, etc.
Posted
by Toby Wilson
on Stack Overflow
See other posts from Stack Overflow
or by Toby Wilson
Published on 2010-04-15T16:00:27Z
Indexed on
2010/04/15
16:03 UTC
Read the original article
Hit count: 620
I'll cut a really long story short and give an example of my problem.
Given a class that has a pointer to a primitive type as a property:
@interface ClassOne : NSObject
{
int* aNumber
}
@property int* aNumber;
The class is instantiated, and aNumber is allocated and assigned a value, accordingly:
ClassOne* bob = [[ClassOne alloc] init];
bob.aNumber = malloc(sizeof(int));
*bob.aNumber = 5;
It is then passed, by reference, to assign the aNumber value of a seperate instance of this type of class, accordingly:
ClassOne* fred = [[ClassOne alloc] init];
fred.aNumber = bob.aNumber;
Fred's aNumber pointer is then freed, reallocated, and assigned a new value, for example 7.
Now, the problem I'm having; Since Fred has been assigned the same pointer that Bob had, I would expect that Bob's aNumber will now have a value of 7. It doesn't, because for some reason it's pointer was freed, but not reassigned (it is still pointing to the same address it was first allocated which is now freed). Fred's pointer, however, has the allocated value 7 in a different memory location.
Why is it behaving like this? What am I minsunderstanding? How can I make it work like C++ does?
© Stack Overflow or respective owner