I've a question about NSMutablearray addobject, I think it's about object lifecycle. Searched but not got answer.
Here's the code:
NSMutableString *str1 = [[NSMutableString alloc]init] ;
NSMutableArray *arr1 = [[NSMutableArray alloc]init] ;
for (int i=0 ;i<3 ;i++) {
str1 =[NSMutableString stringWithFormat:@"%ld",(random() % 100) ] ;
[arr1 addObject:str1] ;
NSLog(@"arr1 inside loop:%@",arr1) ;
[str1 setString:@""] ; }
NSLog(@"arr1 outside loop:%@",arr1) ;
NSMutableString *str2 = [[NSMutableString alloc]init] ;
NSMutableArray *arr2 = [[NSMutableArray alloc]init] ;
for (int i=0 ;i<3 ;i++) {
str2 =[NSMutableString stringWithFormat:@"%ld",(random() % 100) ] ;
[arr2 addObject:str2] ; }
[str2 setString:@"abc"] ;
NSLog(@"arr1:%@",arr2) ;
I expect that arr1 & arr2 both include 3 random number objects.
but the real output is:
arr1 inside loop:(
83
)
arr1 inside loop:(
"",
86
)
arr1 inside loop:(
"",
"",
77
)
arr1 outside loop:(
"",
"",
""
)
arr2:(
15,
93,
abc
)
Q1: Arr1, why the added objects changed to ""?
(If the reason is all 3 objects are just 3 pointers and they point to the same object, then I have Q2 --)
Q2: Arr2, why the last object of arr2 is "abc" but the others not.
Thanks!