Rectangle 27 68

NSDictionary *dict = [NSDictionary dictionaryWithObjects:records 
                                   forKeys:[records valueForKey:@"intField"]];

FYI this is possible because of this built-in feature:

@interface NSArray(NSKeyValueCoding)

/* Return an array containing the results of invoking -valueForKey: 
on each of the receiver's elements. The returned array will contain
NSNull elements for each instance of -valueForKey: returning nil.
*/
- (id)valueForKey:(NSString *)key;

iphone - Convert NSArray to NSDictionary - Stack Overflow

iphone objective-c nsarray nsdictionary
Rectangle 27 50

- (NSDictionary *) indexKeyedDictionaryFromArray:(NSArray *)array 
{
  id objectInstance;
  NSUInteger indexKey = 0U;

  NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init];
  for (objectInstance in array)
    [mutableDictionary setObject:objectInstance forKey:[NSNumber numberWithUnsignedInt:indexKey++]];

  return (NSDictionary *)[mutableDictionary autorelease];
}

iphone - Convert NSArray to NSDictionary - Stack Overflow

iphone objective-c nsarray nsdictionary
Rectangle 27 9

This adds a category extension to NSArray. Needs C99 mode (which is the default these days, but just in case).

In a .h file somewhere that can be #imported by all..

@interface NSArray (indexKeyedDictionaryExtension)
- (NSDictionary *)indexKeyedDictionary
@end

In a .m file..

@implementation NSArray (indexKeyedDictionaryExtension)

- (NSDictionary *)indexKeyedDictionary
{
  NSUInteger arrayCount = [self count];
  id arrayObjects[arrayCount], objectKeys[arrayCount];

  [self getObjects:arrayObjects range:NSMakeRange(0UL, arrayCount)];
  for(NSUInteger index = 0UL; index < arrayCount; index++) { objectKeys[index] = [NSNumber numberWithUnsignedInteger:index]; }

  return([NSDictionary dictionaryWithObjects:arrayObjects forKeys:objectKeys count:arrayCount]);
}

@end
NSArray *array = [NSArray arrayWithObjects:@"zero", @"one", @"two", NULL];
NSDictionary *dictionary = [array indexKeyedDictionary];

NSLog(@"dictionary: %@", dictionary);
2009-09-12 08:41:53.128 test[66757:903] dictionary: {
    0 = zero;
    1 = one;
    2 = two;
}

I love using categories, so I'd preffer this solution instead of using a simple function because of the way of calling it directly on the object itself, as if it always knew that method.

iphone - Convert NSArray to NSDictionary - Stack Overflow

iphone objective-c nsarray nsdictionary
Rectangle 27 2

This is an example of creating a NSMutableDictionary from the employee list NSMutableArray:

NSMutableArray *emloyees = [[NSMutableArray alloc]initWithObjects:@"saman",@"Ruchira",@"Rukshan",@"ishan",@"Harsha",@"Ghihan",@"Lakmali",@"Dasuni", nil];

 NSMutableDictionary *dict = [NSMutableDictionary dictionary];
 for (NSString *word in emloyees) {
 NSString *firstLetter = [[word substringToIndex:1] uppercaseString];
 letterList  = [dict objectForKey:firstLetter];

if (!letterList) {
    letterList = [NSMutableArray array];
    [dict setObject:letterList forKey:firstLetter];
}
[letterList addObject:word];}  NSLog(@"dic %@",dict);

iphone - Convert NSArray to NSDictionary - Stack Overflow

iphone objective-c nsarray nsdictionary
Rectangle 27 1

- (NSDictionary *) indexKeyedDictionaryFromArray:(NSArray *)array
{
    NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init];
    [array enumerateObjectsUsingBlock:
     ^(id obj, NSUInteger idx, BOOL *stop){
         NSNumber *index = [NSNumber numberWithInteger:idx];
         [mutableDictionary setObject:obj forKey:index];
     }];
    NSDictionary *result = [NSDictionary.alloc initWithDictionary:mutableDictionary];
    return result;
}

iphone - Convert NSArray to NSDictionary - Stack Overflow

iphone objective-c nsarray nsdictionary
Rectangle 27 10

NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
  [NSArray arrayWithObjects:@"Spaghetti Pasta", @"Tomato Sauce", nil], @"Spaghetti",
  [NSArray arrayWithObjects:@"Fettuccine Pasta", @"Alfredo Sauce", nil], @"Fettuccine Alfredo",
  [NSArray arrayWithObjects:@"Lettuce", @"Grilled Chicken", @"Croutons", nil], @"Grilled Chicken Salad",
  nil];

You can add any object type to a dictionary as a value. For more on dictionaries, see the documentation.

iphone - How to store an NSArray in an NSDictionary? - Stack Overflow

iphone objective-c nsarray nsdictionary
Rectangle 27 8

You can't just cast a string as a dictionary and expect it to parse the JSON. You must use a JSON parsing library to take that string and convert it into a dictionary.

For a list of JSON libraries for Objective-C, take a look at cocoaobjects.com/?s=json

ios - Convert JSON feed to NSDictionary - Stack Overflow

ios objective-c nsarray nsdictionary sbjson
Rectangle 27 8

You can't just cast a string as a dictionary and expect it to parse the JSON. You must use a JSON parsing library to take that string and convert it into a dictionary.

For a list of JSON libraries for Objective-C, take a look at cocoaobjects.com/?s=json

ios - Convert JSON feed to NSDictionary - Stack Overflow

ios objective-c nsarray nsdictionary sbjson
Rectangle 27 190

NSSortDescriptor
NSSortDescriptor * descriptor = [[NSSortDescriptor alloc] initWithKey:@"interest" ascending:YES];
stories = [stories sortedArrayUsingDescriptors:@[descriptor]];
recent = [stories copy];

stories is the array you want to sort. recent is another mutable array which has sorted dictionary values. Change the @"interest" with the key value on which you have to sort.

+1 This is by far the simplest method

This is good, but it does leak. 1) the sort descriptor should be released or autoreleased, and 2) The copy call is not needed the line can be deleted.

You can use NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"interest" ascending:YES];

ios - Best way to sort an NSArray of NSDictionary objects? - Stack Ove...

ios objective-c sorting nsarray nsdictionary
Rectangle 27 96

With IOS5 you can use NSJSONSerialization for serializing the JSON.

NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

NSJSONWritingPrettyPrinted is a writing option for use in writeJSONObject:, if you use it in this context you'll get the effect of NSJSONReadingMutableContainers applied to the read.

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&writeError]; //    NSString *strJsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];     NSDictionary *dicJsonRequest = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&convertError];

Error is also null.what is wrong with this line.I have copy pasted your code

ios - Convert JSON feed to NSDictionary - Stack Overflow

ios objective-c nsarray nsdictionary sbjson
Rectangle 27 96

With IOS5 you can use NSJSONSerialization for serializing the JSON.

NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

NSJSONWritingPrettyPrinted is a writing option for use in writeJSONObject:, if you use it in this context you'll get the effect of NSJSONReadingMutableContainers applied to the read.

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&writeError]; //    NSString *strJsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];     NSDictionary *dicJsonRequest = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&convertError];

Error is also null.what is wrong with this line.I have copy pasted your code

ios - Convert JSON feed to NSDictionary - Stack Overflow

ios objective-c nsarray nsdictionary sbjson
Rectangle 27 24

[array sortUsingDescriptors:[NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"YOUR-KEY" ascending:YES], nil]];

I don't really want to break it into multiple lines. It's already simple enough for me.

ios - Best way to sort an NSArray of NSDictionary objects? - Stack Ove...

ios objective-c sorting nsarray nsdictionary
Rectangle 27 1

I want to create a NSdictionary with the districts as a key and the value for that key is an array with the points that are in that district.

[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) {
        NSMutableDictionary *dict = [@{} mutableCopy];

        for (Points *point in objects) {
            // if no point for that district was added before,
            // initiate a new array to store them
            if (![dict containsKey:point.district])
                dict[point.district] = [@[] mutableCopy];

            [dict[point.district] addObject:point];
        }     

        block(dict, error);

    } else {
        NSLog(@"Error: %@ %@", error, [error userInfo]);
    }
}];

I didn't know you can use a dictionary like an array :\, so its also not a problem how the objects are sorted in the objects array ? Or would it be better for performance ?

Yeah, you have to add a new mutable array as a value of a district every time a point of some district was not added before. For the next points of that district, a mutable array will be there an you just need to append that new point.

ios - Split nsarray to nsdictionary - Stack Overflow

ios objective-c nsarray nsdictionary
Rectangle 27 140

Please Try the following Code.

NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                     options:kNilOptions 
                                                       error:&error];

NSArray* latestLoans = [json objectForKey:@"loans"];

NSLog(@"loans: %@", latestLoans);

then enter your url in browser and then you will get dict or array then copy all data and paste it in this link jsonlint.com if your json is valid then it will show or if there is any error then will show null.

iphone - How to convert JSON serialized data to NSDictionary - Stack O...

iphone objective-c ios json
Rectangle 27 140

Please Try the following Code.

NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                     options:kNilOptions 
                                                       error:&error];

NSArray* latestLoans = [json objectForKey:@"loans"];

NSLog(@"loans: %@", latestLoans);

then enter your url in browser and then you will get dict or array then copy all data and paste it in this link jsonlint.com if your json is valid then it will show or if there is any error then will show null.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

iphone - How to convert JSON serialized data to NSDictionary - Stack O...

iphone objective-c ios json
Rectangle 27 9

You can just traverse from the parent to the required child property. For e.g.

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"parent.child.child"  ascending:YES];

You little star. this helped me sort a sub sub dictionary. Thanks a lot!

ios - Best way to sort an NSArray of NSDictionary objects? - Stack Ove...

ios objective-c sorting nsarray nsdictionary
Rectangle 27 2

First You must change you structure into NSDictionary class and NSArray containing NSDictionary objects, then try JSONKit in iOS 5 serialization works better than standard NSJSONSerialization.

iphone - Converting an NSArray of Dictionaries to JSON array in iOS - ...

iphone json cocoa cocoa-touch nsarray
Rectangle 27 22

If you want to see an NSArray and NSDictionary and etc objects then you can directly print like NSLog(@"%@",object);

If it is an user defined object then you need to display by calling with property(attribute).

User defined object with name object and properties like

NSString *property1;
int property2;
NSMutableArray *property3;
NSLog(@"%@, %d, %@" object.property1,object.property2,object.property3);

what are properties are showing?

iphone - How can I see values of Object in NSLog? - Stack Overflow

iphone objective-c object nslog
Rectangle 27 140

Please Try the following Code.

NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                     options:kNilOptions 
                                                       error:&error];

NSArray* latestLoans = [json objectForKey:@"loans"];

NSLog(@"loans: %@", latestLoans);

then enter your url in browser and then you will get dict or array then copy all data and paste it in this link jsonlint.com if your json is valid then it will show or if there is any error then will show null.

iphone - How to convert JSON serialized data to NSDictionary - Stack O...

iphone objective-c ios json
Rectangle 27 186

Here are categories for NSArray and NSDictionary to make this super-easy. I've added an option for pretty-print (newlines and tabs to make easier to read).

@interface NSDictionary (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint;
@end
@implementation NSDictionary (BVJSONString)

  -(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint {
     NSError *error;
     NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
                                                   options:(NSJSONWritingOptions)    (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
                                                     error:&error];

     if (! jsonData) {
        NSLog(@"bv_jsonStringWithPrettyPrint: error: %@", error.localizedDescription);
        return @"{}";
     } else {
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
     } 
 }
@end
@interface NSArray (BVJSONString)
- (NSString *)bv_jsonStringWithPrettyPrint:(BOOL)prettyPrint;
@end
@implementation NSArray (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
                                                       options:(NSJSONWritingOptions) (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
                                                         error:&error];

    if (! jsonData) {
        NSLog(@"bv_jsonStringWithPrettyPrint: error: %@", error.localizedDescription);
        return @"[]";
    } else {
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
}
@end

if we create a category of NSObject and put the same method, it works for both NSArray and NSDictionary. No need to write two separate files/interfaces. And it should return nil in case of error.

Why do you assume that NSUTF8StringEncoding is the correct encoding?

Nevermind, the documentation says "The resulting data is a encoded in UTF-8."

@AbdullahUmer That's what I've done too as I presume it'll also work on NSNumber, NSString, and NSNull will find out in a minute or two!

objective c - Generate JSON string from NSDictionary in iOS - Stack Ov...

ios objective-c json string