0

I have some confusion. Not really a bug or issue I am facing. I want to know something and I am not sure this is right place for this kind of question but here is my question:

In reference to my Question Here I was trying to map single gesture on two views.

Now I am keen to know that why this is not working? I went on basics that in case I have any NSObject subclass lets say if NSString and I add this in an NSMutableArray as follows:

 NSString *strTest = @"Test String";
 [aryTest1 addObject:strTest];
 [aryTest2 addObject:strTest];

String gets added in both of array. Now what I am doing is I created a label, set tag for the label and added that in two views as follows:

 UILabel *lblTemp = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 20)];
[lblTemp setTag:1];
[lblTemp setText:@"Label"];
[vw1 addSubview:lblTemp];
[vw2 addSubview:lblTemp];

Now every view has an array of subview. When we try to add an object in that view's subview why this is not being added in both of view? I am getting a result that my second view is showing the label but first view is not having the label.

If I comment the last line of my code and don't add label in vw2 the label will be added in vw1. Than I tried a different thing.

UILabel *lblTemp = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 20)];
[lblTemp setTag:1];
NSMutableArray ary1 = [[NSMutableArray alloc] init];
NSMutableArray ary2 = [[NSMutableArray alloc] init];
[ary1 addObject:lblTemp];
[ary2 addObject:lblTemp];

both array has count 1. Thats mean that I have label added in my array. after that I tried to add array's object in view than even ame problem. Label is only being added in second view:

 [vw1 addSubview:[ary1 objectAtIndex:0]];
 [vw2 addSubview:[ary2 objectAtIndex:0]];

When I printed retainCount of Label after initialize, adding in array1 and array2 everytime the retaincount was 1. So I think the array are not keeping the reference of same object. Its a new object copied in array. Than why label is not being added in same view?

What is actual internal process for a object to add on any view's subview. As of I know subview is an Array type than what happening? Can anyone explain me?

Thanks in Advance

Community
  • 1
  • 1
Kapil Choubisa
  • 5,152
  • 9
  • 65
  • 100

1 Answers1

0

The difference is that addSubview automatically removes a view from it's super view before adding it to the new view (See the class reference: http://developer.apple.com/library/ios/ipad/#documentation/uikit/reference/uiview_class/uiview/uiview.html) while an array will happily accept an object even if it is in another array.

You can create a copy of the label and place it in the other view though if this is what you need to do.

lnafziger
  • 25,760
  • 8
  • 60
  • 101