0

I made a small code

NSArray* _options = [NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:[UIImage    imageNamed:@"2"],@"img",name,@"text"
                                   , nil],nil];

Now, I want add other object to _options. What should i do? I make more test but no success. Thank for all

4 Answers 4

2

you can use [NSArray arrayByAddingObject:]

_options = [_options arrayByAddingObject:object];

or change _options to NSMutableArray

NSMutableArray *_options = [NSMutableArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:[UIImage    imageNamed:@"2"],@"img",name,@"text"
                                   , nil],nil];
[_options addObject:object];

and you may want to use modern syntax

NSMutableArray *_options = [@[@{@"img":[UIImage imageNamed:@"2"],@"text":name}] mutableCopy];
[_options addObject:object];
Sign up to request clarification or add additional context in comments.

Comments

2

NSArray does not allow any changes to be made; you can use an NSMutableArray instead like this:

NSMutableArray *mutable = [_options mutableCopy];

[mutable addObject:yourObject];

NSDictionary is same in that it can't be mutated.

Comments

1

You can't add objects to a NSArray, to do so, you need a NSMutableArray.

However, you can add objects to NSArray when creating it with : arrayWithObjects

Comments

1

First, create an NSMutableArray, as you can make changes to it as you see fit later throughout your code:

NSMutableArray *newOptions = [NSMutableArray alloc]init];

[newOptions setArray:_options];

[newOptions addObject:yourObject];

3 Comments

NSArray does not have method addObject: I downvote it because this is wrong answer.
I want to downvote it again. newOptions = _options doesn't magically change _options to NSMutableArray
another downvote, you should use setArray: not addObject:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.