Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

ios - NSMutableArray addObject getting set to nil after release of object

I have declared an NSMutableArray *arrAllRecordsM and am trying to add NSMutableDictionary *dicRecordM to it using addObject. The dicRecordM gets added to arrAllRecordsM but on doing [dicRecordM removeAllObjects] it sets to nil in arrAllRecordsM. Below is the code, please help me fix it.

self.arrAllRecordsM = [NSMutableArray array];
self.dicRecordM = [NSMutableDictionary dictionary];

// Some Method

[self.dicRecordM setObject:@"Test" forKey:@"ADDRESS"];
[self.arrAllRecordsM addObject:self.dicRecordM];

// Value: Test
NSLog(@"Value: %@", [[self.arrAllRecordsM objectAtIndex:0] valueForKey:@"ADDRESS"]);
[self.dicRecordM removeAllObjects];

// Value: null
NSLog(@"Value: %@", [[self.arrAllRecordsM objectAtIndex:0] valueForKey:@"ADDRESS"]); 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Adding an object to an NSMutableArray just stores a pointer (or "strong reference") to the object into the array. Therefore

[self.arrAllRecordsM objectAtIndex:0]

and

self.dicRecordM

are two pointers to the same object. If your remove all key/value pairs from self.dicRecordM then [self.arrAllRecordsM objectAtIndex:0] still points to the same (now empty) dictionary. That is the reason why

[[self.arrAllRecordsM objectAtIndex:0] valueForKey:@"ADDRESS"]

returns nil.

If you want an independent copy of the dictionary in the array, use

[self.arrAllRecordsM addObject:[self.dicRecordM copy]];

copy can be used on many classes, such as NSDictionary, NSArray and NSString and their mutable variants, to get a "functionally independent object". Formally, it is available for all classes conforming to the NSCopying protocol.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...