开发者

some problem with variables in objective-c

开发者 https://www.devze.com 2023-03-11 17:07 出处:网络
Here is what I am doing : [imageTag.mediaTags addObject:unitTag]; [imageTag.allTags addObject:unitTag];

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 figure开发者_JAVA百科d 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.


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消