iYahoo
iYahoo

Reputation: 184

How to add a returned NSArray to a NSArray

I am new to Objective-C and iPhone

I have to sort a NSDictionary using values and according to that i have to arrange the keys of that values, i have sorted the array.

//getting values
NSArray* keys1 = [sortDictionary allValues];    
NSArray* sortedArray = [keys1 sortedArrayUsingComparator:^(id a, id b) {  
     return [a compare:b options:NSNumericSearch];
}]; 

My problem now is I am getting the keys of the values by allKeysForObject: , which returns an NSArray.

for( NSString* aStr in sortedArray ) {
    NSLog( @"%@ has value %@", [sortDictionary allKeysForObject:aStr], aStr );  
 }    
O/P :- (
  Sourish
) has value 60

Rather i want "Sourish" as a string and store it to a NSArray and than store that NSArray to NSDictionary or store both Sourish and 60 to another NSDictionary

Kindly make me to sort our this problem.

Upvotes: 2

Views: 220

Answers (3)

The iOSDev
The iOSDev

Reputation: 5267

you can use NSMutableArray to store your data using addObject: selector or use NSMutableDictionary to store both as key:value pare using addObjectsAndKeys: selector

Upvotes: 0

Obliquely
Obliquely

Reputation: 7072

This gets the string for you by looking at the array. Is that what you are after?

NSDictionary* sortDictionary = [NSDictionary dictionaryWithObjectsAndKeys: @"60", @"Sourish", @"45" , @"Peckish",  @"25", @"Swordfish", @"15", @"Mashmish", nil];

 NSArray* keys1 = [sortDictionary allValues];    
 NSArray* sortedArray = [keys1 sortedArrayUsingComparator:^(id a, id b)
 {  
    return [a compare:b options:NSNumericSearch];
 }]; 

 for( NSString* aStr in sortedArray )
 {
    NSString* keyForObject = @"";

    if ([[sortDictionary allKeysForObject: aStr] count] > 0)
    {
        keyForObject = [[sortDictionary allKeysForObject: aStr] objectAtIndex: 0];
    }

     NSLog( @"%@ has value %@", keyForObject, aStr );  
 }  

This logs:

Mashmish has value 15
Swordfish has value 25
Peckish has value 45
Sourish has value 60

Upvotes: 2

Vignesh
Vignesh

Reputation: 10251

">> I have to sort a NSDictionary using values and according to that i have to arrange the keys of that values"

NSArray *allkey =[[NSArray alloc] initWithArray:[sortDictionary keysSortedByValueUsingSelector:@selector(compare:)]] ;

Implement your compare method,

 - (NSComparisonResult)compare:(id)b {
    return [self compare:b options:NSNumericSearch];
}

The allkey is the keys array sorted using values.

Upvotes: 0

Related Questions