user1256477
user1256477

Reputation: 11201

NSArray and NSDictionary

I have an NSDictionary and I have to add it to a NSArray. How can I do it?

NSDictionary *row = [NSDictionary dictionaryWithObjectsAndKeys:
     [NSString stringWithFormat:@"%@",NSLocalizedString(@"no_favorites", nil)], @"Address", nil];

If I use:

    aFavorite = [row allValues];

as sugested, if I print it I got:

(
"No favorites added"
)

What I need is:

  (
    {
    Address = "No favorites added";
 }
 )

Because I will use:

NSDictionary* dict = [aFavorite objectAtIndex:[indexPath row]];
 NSString *contentForThisRow = [dict objectForKey:@"Address"];

The dict value can have 1 or 2 keys.

Upvotes: 0

Views: 5605

Answers (4)

janusfidel
janusfidel

Reputation: 8106

NSDictionary *row = [NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:@"%@",NSLocalizedString(@"no_favorites", nil)], @"Address", nil];
[aFavorite addObject:row];

then:

NSDictionary* dict = [aFavorite objectAtIndex:[indexPath row]];
NSString *contentForThisRow = [dict objectForKey:@"Address"];

I have an NSDictionary and I have to add it to a NSArray

if you meant add the NSDictionary to NSArray in runtime, sorry you cant do that, NSArray is immutable.

Upvotes: 0

Scar
Scar

Reputation: 3480

To convert a Dictionary you can use it's method:

myArray = [[NSArray alloc] initWithArray:[myDic allValues]];

UPDATE

When you want to add the dic in order to retrive it and use the key to retrive the value, use NSMutableArray like this:

NSMutableArray *myArray = [[NSMutableArray alloc] init];
[myArray addObject:myDic];

Then retrive the dic simply by using:

NSDictionary *myDic = [myArray objectAtIndex:indexPath.row];
NSString *value = [myDic objectForKey:@"myValue"];

Upvotes: 7

Sameer
Sameer

Reputation: 17

it you want to access all values then try it:- NSArray * values = [dictionary allValues];

if access all keys try it :- NSArray * values = [dict allValues];

Upvotes: 0

TeaCupApp
TeaCupApp

Reputation: 11452

Call allValues function of NSDictionary, it will return NSArray of all the values.

NSArray *array = [row allValues];

To get NSArray for keys, use,

NSArray *array = [row allKeys];

Reference link : Apple Doc


Well thats a basic programming logic with some string concatinations. If you want "key value pairs" then you must use NSDictionary. but if you want Address = Something then get all keys in one array and get all values in different array and then loop them in single loop.

Upvotes: 2

Related Questions