in classA i have :
classB *classBI=[[classB alloc]init];
bits=[classBI data]; //bits has a property here in classA,it gets data from B/
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(38.f, 20.f, 244.f, 43.f)];
label.text = bits;
in classB i have :
@property (nonatomic,retain) NSString *data; //in .h file
data=@"no data"; //at the init method of classB .
//then after a while when something is happen in classB , data is changed to :
data=[NSString stringWithFormat:@"data:%f,%f,%f,%f,%f,%f",
dataBits[0],dataBits[1],dataBits[2],dataBits[3],dataBits[4],dataBits[5] ];
classA is the main scene (cocos2d but it does not matter). at the start i can really see in the label that in classA the word “no data”, but when data is changed in classB, i cant see that change in the label that is on screen. it stay with the word: “no data ”
why is that ?
why i lost data ?
if i NSLOG data in classB ,right after it changed in there,i can see that its not null,and it has the new value. something is wrong with the instance of B ,in A, that get this string.
When you set the label’s text to the string pointed to by
bits, it is storing a reference to that string. Later when you changedata, it is creating a new string whichdatais pointing to, butbitsand the label both still have the original pointer which is looking at the original string. You want to update them wheneverdatais changed:There are several approaches to take in this situation, but one of the easiest would be to observe the
dataproperty ofclassBIfor changes, and update bothbitsand the label whenever it changes:Then, whenever data changes, this method will be called: