Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a NSMutableArray from a NSArray Objective-C

I have an NSArray that gives me the following data:

01/14/2013 13:28:06.559 IUser Reader [71164: c07] (
         {
         "id_acompanhante" = "";
         "id_evento" = 34;
         "user_id" = 1;
         "inserido_por" = "Himself";
         name = iUser;
         status = done;
         type = User;
     }
         {
         "id_acompanhante" = 1;
         "id_evento" = 34;
         "user_id" = 1;
         "inserido_por" = iUser;
         name = "Mayara Roca";
         status = naofeito;
         type = companion;
     }
)

How do I play this data to a NSMutableArray and add another field within each item. example:

  {
     "id_acompanhante" = "";
     "id_evento" = 34;
     "user_id" = 1;
     "inserido_por" = "Himself";
     name = IUser;
     status = done;
     type = User;
     tag = 2;
 }

I added one more field "TAG".

How do I do this?

like image 338
Halan Schlickmann Avatar asked Jan 14 '13 15:01

Halan Schlickmann


People also ask

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

How do you declare NSArray in Objective-C?

Creating NSArray Objects Using Array Literals In addition to the provided initializers, such as initWithObjects: , you can create an NSArray object using an array literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method.

How do you reverse an NSArray?

You can reverse a NSArray by writing your own loop iterating from the end towards the beginning and using a second array to add the items in reverse order. Or you can simply use - (NSEnumerator *)reverseObjectEnumerator from the NSArray class.

Can NSArray contain nil?

arrays can't contain nil. There is a special object, NSNull ( [NSNull null] ), that serves as a placeholder for nil.


2 Answers

NSMutableArray *mutableArray = [NSMutableArray array];

for (NSDictionary *dictionary in yourArray) {
    NSMutableDictionary *mutDictionary = [dictionary mutableCopy];

    [mutDictionary setObject:[NSNumber numberWithInt:2] forKey:@"tag"];

    [mutableArray addObject:mutDictionary];
}

This is how to do what you asked. Making the array mutable will not allow you to change the contents of a dictionary inside it. You need to pull out each dictionary and make that mutable and then store it back in the array.

like image 107
Fogmeister Avatar answered Oct 21 '22 15:10

Fogmeister


Easy

NSMutableArray *mArray = [NSMutableArray arrayWithArray:yourArray]
[mArray addObject:yourObject];
like image 7
Volodymyr B. Avatar answered Oct 21 '22 14:10

Volodymyr B.