Antonio Madonna
Antonio Madonna

Reputation: 919

Replace content of NSMutableArray with NSArray

I'm working on an app that needs to retrieve some data from a server. I have created a "Server" class which handles all the communication and has a NSMutableArray *sessionData variable where I would like to store the data coming from the server (btw, is this approach correct?).

I have the data in an NSArray. I would like the NSMutableArray to have the same content of the NSArray but I didn't find any way to do this (sessionData = requestResult).

(subquestion: do I have to initialize in some way the NSMutableArray before using ? I have only declared it with @property and @synthesize)

Upvotes: 3

Views: 957

Answers (5)

h4cky
h4cky

Reputation: 894

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

Upvotes: 0

Himanshu A Jadav
Himanshu A Jadav

Reputation: 2306

1. is this approach correct?

Yes.

2. I didn't find any way to do this (sessionData = requestResult)

As many have suggested you can use mutableCopy to assign requestResult to sessionData OR you can use arrayWithArray as one answer suggests.

3. do I have to initialize in some way the NSMutableArray before using ?

Yes. If you are changing any variable it must have memory allocated.

Upvotes: 0

user1040049
user1040049

Reputation:

Or, if you could do this:

NSMutableArray *session = [NSMutableArray arrayWithArray:someArray];

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

The code you tried (from the comment) should have worked. The reason it did not work is that your sessionData was nil.

You need to initialize your sessionData - set it to [NSMutableArray array] in the initializer; then your code

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

will work perfectly. You do not even need the first line - the second one replaces the content of sessionData with that of the result.

Upvotes: 5

Alexander
Alexander

Reputation: 8147

Try this way:

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

Or

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

Upvotes: 4

Related Questions