Ahsan
Ahsan

Reputation: 2982

some problem with variables in objective-c

Here is what I am doing :

    [imageTag.mediaTags addObject:unitTag];
    [imageTag.allTags addObject:unitTag];

    unitTag.title=@"";
    unitTag.link=@"";
    unitTag.description=@"";
    unitTag.price=@"";
    unitTag.imageLink=@"";

The problem is, once I make execute beyond line 2, the values stored in the array gets lost too (I used GDB to print and figured that out). Now the thing is, I am reusing the unitTag object to enter some information and saving that information inside an array. So what are my options ? I need to delete the values because some of the values are optional and I dont want to mess up.

Can anyone please kindly let me know ? Thanks.

Upvotes: 0

Views: 849

Answers (1)

NG.
NG.

Reputation: 22904

If I understand correctly, you need to make a copy of the UnitTag object and insert that into the array. You're just storing an object reference in the array and then nuking the values the reference is using.

addObject is not storing a copy - it's storing the actual object reference.

To make a copy, you need to create a new object that unitTag is, and then add it. So potentially your code could be:

id unitTagCopy = [unitTag createCopy];
[imageTag.mediaTags addObject:unitTagCopy];
[imageTag.allTags addObject:unitTagCopy];

You'd have to add the createCopy method. I imagine it could be:

-(id) createCopy {
    MyObj* obj = [[[MyObj] init] alloc] autorelease];
    obj.title= self.title;
    obj.link= self.link;
    obj.description= self.description;
    obj.price= self.price;
    obj.imageLink= self.imageLink;
    return obj;
}

Upvotes: 1

Related Questions