Replace NSMutableArray content with NSArray

I am working on an application that needs to receive some data from the server. I created a Server class that handles all messages and has a sessionData NSMutableArray * variable where I would like to store the data coming from the server (by the way, is this approach correct?).

I have data in NSArray. I would like the NSMutableArray to have the same NSArray content, but I haven't found a way to do this (sessionData = requestResult).

(subquestion: do I need to initialize NSMutableArray somehow before using it? I just declared it with @property and @synthesize)


source to share

5 answers

Try this way:

sessionData = [result mutableCopy];
[result release];



NSMutableArray *sessionData = [[NSMutableArray alloc] initWithContentsOfArray:result];




The code you tried (from the comment) should work. The reason it didn't work is because yours sessionData

was nil


You need to initialize sessionData

- set it to [NSMutableArray array]

in the initializer; then your code

[sessionData removeAllObjects];
[sessionData setArray:result];


will work fine. You don't even need the first line - the second replaces content sessionData

with content result




Or, if you can do this:

NSMutableArray *session = [NSMutableArray arrayWithArray:someArray];




In your example, something like this:

NSArray *requestData = [[NSArray alloc] initWithObjects:@"3", @"4", @"5", nil];
_sessionData = [[NSMutableArray alloc] initWithArray:requestData];
[requestData release];

NSLog(@"%@", [sessionData objectAtIndex:0]); // 2012-03-30 15:53:39.446 <app name>[597:f803] 3
NSLog(@"count: %d", [sessionData count]); //2012-03-30 15:53:39.449 <app name>[597:f803] count: 3




1. is this approach correct?


2. I haven't found any way to do this (sessionData = requestResult)

As said, you can use mutableCopy

to assign requestResult


OR you can use arrayWithArray

as one answer suggests.

3.Do I need to initialize NSMutableArray somehow before use?

Yes. If you change any variable, it must have memory allocated.



All Articles