简体   繁体   中英

How to copy the contents of NSMutableArray to another NStArray in iphone app?

I have two array one is NSMutableArray and one is NSArray i want to store the contents of NSMutableArray in NSArray but it is not working for me gives exception unrecognised selector sent.

myArray=[[NSArray alloc] initWithArray:appDelegate.surveyAnswersScreenOne];

Note, SurveyAnswerScreenOne is an NSMutableArray

You can do that in many ways -

NSArray * myArray = [appDelegate.surveyAnswersScreenOne copy];

NSArray * myArray = [NSArray arrayWithArray:appDelegate.surveyAnswersScreenOne];

NSArray * myArray = [[NSArray alloc]initWithArray:appDelegate.surveyAnswersScreenOne];

But first of all your appDelegate.surveyAnswersScreenOne should have objects in it.

From what we see here, it is most likely that your mutable array is nil. Look into the creation of that in you app delegate. If it is created properly, check that it is retained. Is it a strong reference?

@propery(nonatomic, strong) NSMutableArray *surveyAnswersScreenOne;

for one, I would use the convenience method:

myArray = [NSArray arrayWithArray:appDelegate.surveyAnswersScreenOne];

If surveyAnswersScreenOne is a valid array, mutable or otherwise, this should work. Try printing it to the console to be sure. This will return empty array if surveyAnswersScreenOne is nil, where alloc initWithArray will fail. Check you mutable array like this.

NSLog(@"Mutable array is %@", appDelegate.surveyAnswersScreenOne);

Have you made object for your appDelegate ?

appDelegate = (yourDelegateClass *)[[UIApplication sharedApplication]delegate];

If yes, then other answers should work!

myArray = [NSArray arrayWithArray:appDelegate.surveyAnswersScreenOne];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM