HurkNburkS
HurkNburkS

Reputation: 5510

how to create an array of NSDictionarys

I would like to fetch the information I have stored into one of my core data objects and store this data into an NSArray of NSDictionary objects, so that I can send this array of to one of my views and display the data in a tableview.

However I am not quite sure how to get the NSDictionary into the NSArray, this is my fetch request as it stands, hopefully someone can give me a hand putting the NSDictionary into a NSArray.. Im not sure how to do this because of how I am looping though the Core Data Object.

// Test listing all FailedBankInfos from the store
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Manuf" inManagedObjectContext:context];
        [fetchRequest setEntity:entity];

        NSError *error; 

        NSMutableDictionary *tempManufacturerDictionary = [[ NSMutableDictionary alloc] init];

        NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
        for (Manuf *manuf in fetchedObjects) {
            [tempManufacturerDictionary setObject:manuf.hasMod forKey:@"HASMOD"];
            [tempManufacturerDictionary setObject:manuf.isLocked forKey:@"ISLOCKED"];
            [tempManufacturerDictionary setObject:manuf.isReg forKey:@"ISREG"];
            [tempManufacturerDictionary setObject:manuf.main forKey:@"MAIN"];

            // How do I put the Dictionary above into an array?
        }

any help would be appreciated.

Upvotes: 1

Views: 263

Answers (2)

Carl Veazey
Carl Veazey

Reputation: 18363

You can instantiate an NSMutableArray before entering the loop, and declare a new NSMutableDictionary during every iteration, like so:

    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    NSMutableArray *array = [NSMutableArray array];
    for (Manuf *manuf in fetchedObjects) {
        NSMutableDictionary *tempManufacturerDictionary = [NSMutableDictionary dictionary];
        [tempManufacturerDictionary setObject:manuf.hasMod forKey:@"HASMOD"];
        [tempManufacturerDictionary setObject:manuf.isLocked forKey:@"ISLOCKED"];
        [tempManufacturerDictionary setObject:manuf.isReg forKey:@"ISREG"];
        [tempManufacturerDictionary setObject:manuf.main forKey:@"MAIN"];

        [array addObject:tempManufacturerDictionary];
    }

You could also set the resultType of your fetch request to be NSDictionaryResultType and get an array of dictionaries from the fetch request in the first place.

Upvotes: 4

Logan Serman
Logan Serman

Reputation: 29880

Just like you would any other object, using addObject.

You need to be using an NSMutableArray though, not a normal NSArray to be able to add elements. You can convert a mutable array into a normal array later if you strictly need an immutable version.

Upvotes: 2

Related Questions