Reputation: 919
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
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
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
Reputation:
Or, if you could do this:
NSMutableArray *session = [NSMutableArray arrayWithArray:someArray];
Upvotes: 0
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
Reputation: 8147
Try this way:
sessionData = [result mutableCopy];
[result release];
Or
NSMutableArray *sessionData = [[NSMutableArray alloc] initWithContentsOfArray:result];
Upvotes: 4