How to create an array with Dictionaries? - iphone

I just need some help in creating an array which can store multiple dictionaries.
I have :
.h
NSArray * projects;
NSDictionary *project1;
NSDictionary * project2;
.m
projects = /* What should I write here to store the
above two dictionaries in my array. */
Thanks,

projects = [[NSArray alloc] initWithObjects:project1, project2, nil];

Basically (and this will be right or not quite right depending on you actual code, declarations, properties, etc). Because you declared projects as an NSArray, you could do the following:
projects = [NSArray arrayWithObjects: project1, project2, nil];
This variable will go away magically when it goes out of scope unless you retain it.
Alternatively, if you declare projects as an NSMutableArray and make a property with attributes (retain, nonatomic), you could do something like this:
NSMutableArray *a = [[NSMutableArray alloc] initWithObjects:project1, project2, nil];
self.projects = a;
[a release];
There are several ways to achieve your goal, depending on your overall needs for the array.

I'm not sure if what you are looking for is more complex then this, but:
projects = [[NSArray alloc ] initWithObjects:project1,project2, nil];
should work.
If you are after something more complex then this let me know I will revise my answer.

arr = [[NSArray alloc ] initWithObjects:dict1,dict2, nil];

Related

How to copy the contents of NSMutableArray to another NStArray in iphone app?

I have two array one is NSMutableArray and one is NSArray i want to store the contents of NSMutableArray in NSArray but it is not working for me gives exception unrecognised selector sent.
myArray=[[NSArray alloc] initWithArray:appDelegate.surveyAnswersScreenOne];
Note, SurveyAnswerScreenOne is an NSMutableArray
You can do that in many ways -
NSArray * myArray = [appDelegate.surveyAnswersScreenOne copy];
NSArray * myArray = [NSArray arrayWithArray:appDelegate.surveyAnswersScreenOne];
NSArray * myArray = [[NSArray alloc]initWithArray:appDelegate.surveyAnswersScreenOne];
But first of all your appDelegate.surveyAnswersScreenOne should have objects in it.
Have you made object for your appDelegate ?
appDelegate = (yourDelegateClass *)[[UIApplication sharedApplication]delegate];
If yes, then other answers should work!
myArray = [NSArray arrayWithArray:appDelegate.surveyAnswersScreenOne];
From what we see here, it is most likely that your mutable array is nil. Look into the creation of that in you app delegate. If it is created properly, check that it is retained. Is it a strong reference?
#propery(nonatomic, strong) NSMutableArray *surveyAnswersScreenOne;
for one, I would use the convenience method:
myArray = [NSArray arrayWithArray:appDelegate.surveyAnswersScreenOne];
If surveyAnswersScreenOne is a valid array, mutable or otherwise, this should work. Try printing it to the console to be sure. This will return empty array if surveyAnswersScreenOne is nil, where alloc initWithArray will fail.
Check you mutable array like this.
NSLog(#"Mutable array is %#", appDelegate.surveyAnswersScreenOne);

iPhone: How to access NSMutableArray two dimensional setting?

I am using insertObject for NSMutableArray for storing values into two dimensional array like below for example.
[mutableArrayPtr insertObject:[NSMutableArray arrayWithObjects:firstData, secondData,nil] atIndex:index];
I think, it is correct way of storing values in two dimensional array in Obj C.
I want to access it at later point of time. How can i do that?
Thanks!
The way you are doing it is perfectly fine. NSArray's don't have native two dimensional syntax like primitive arrays (int[][], double[][], etc.) in C do. So instead, you must nest them using an array of arrays. Here's an example of how to do that:
NSString *hello = #"Hello World";
NSMutableArray *insideArray = [[NSMutableArray alloc] initWithObjects:hello,nil];
NSMutableArray *outsideArray = [[NSMutableArray alloc] init];
[outsideArray addObject:insideArray];
// Then access it by:
NSString *retrieveString = [[outsideArray objectAtIndex:0] objectAtIndex:0];
To access your array at a later point in time, you would do something like:
NSArray* innerArray = [mutableArrayPtr objectAtIndex:0];
NSObject* someObject = [innerArray objectAtIndex:0];
Of course, change 0 to whatever index you actually need to retrieve.
EDIT:
Q: Is it "initWithObjects" (or) "insertObject:[NSMutableArray arrayWithObjects:imagePtrData,urlInStr,nil]" for two dimension?
A: initWithObjects and insertObject would both allow you to create two dimensional arrays. For example you could do:
NSMutableArray* arrayOne = [[NSMutableArray alloc] initWithObjects:[NSArray initWithObjects:#"One", #"Two", #"Three", nil], [NSArray initWithObjects:[#"Four", #"Five", #"Six", nil], nil];
// NOTE: You need to release the above array somewhere in your code to prevent a memory leak.
or:
NSMutableArray* arrayTwo = [NSMutableArray array];
[arrayTwo insertObject:[NSArray arrayWithObjects:#"One", #"Two", #"Three", nil] atIndex:0];

Objective C two-dimensional array memory issues

I'm trying to declare a two-dimensional array as an instance variable in Objective C. I've got the NSMutableArray in the header (data), along with the #property (nonatomic, retain). In viewDidLoad: I have:
data = [[NSMutableArray alloc] init];
[data addObject:[[NSArray alloc] initWithObjects:#"Cheese", #"Meat", #"Veggie", nil]];
[data addObject:[[NSArray alloc] initWithObjects:#"Sandwich", #"Soup", #"Stew", nil]];
I can NSLog the array within the method and it is correct, however when I try to Log it from a separate method I get nothing (just "#"), and if I try to access with
NSInteger num = [[data objectAtIndex:component] count];
it crashes with no error in the log. I'm sure this is something to do with not allocating memory properly, however I am new to Obj C and haven't worked with a C-style language in many years. FWIW, I have tried many variants of this that all fail, including using NSArray instead of mutable, [NSArray arrayWithObjects] instead of [[NSArray alloc] initWithObjects], and every combination in between.
try creating the outer array like this:
self.data = [NSMutableArray arrayWithCapacity:2]; // assuming you're only adding 2 inner arrays.
The following may be a right way.
self.data = [NSMutableArray array];
[data addObject:[NSArray arrayWithObjects:#"Cheese", #"Meat", #"Veggie", nil];
[data addObject:[NSArray arrayWithObjects:#"Sandwich", #"Soup", #"Stew", nil];
Note that, as #jamihash commented above, you need self.data to properly retain the array. And, there is no need to alloc the NSArray which you are adding to data.
As a side issue, you're retaining the child arrays twice. They get retained when you add them to your NSMutableArray, so you should probably autorelease them on creation or create them with one of the NSArray methods that returns an autoreleased array.
Your code by itself shouldn't crash. You should look into where and when you release and retain the NSMutableArray. You could post more of the code and I'm sure somebody will spot the problem.

iPhone, I need to reuse an NSArray which has constant values in different views, how?

I have the following array.
NSArray *arrayDisplay = [[NSArray alloc] initWithObjects:#"Daily",
#"Weekly", #"Monthly", nil];
I need to use it in two views, I'm concerned that I may make changes and forget to change the other in the future. So I'd like to declare it once and reuse it.
How should I do this?
You can keep it as a property in a common object such as the application delegate.
Assuming its nonatomic,retain type property then access it like:
myAppDelegate *del = [[UIApplication sharedApplication] delegate];
del.arrayDisplay = [NSArray arrayWithObjects:#"Daily",#"Weekly", #"Monthly", nil];
Although if you plan on changing it you might want an NSMutableArray.
Consider writing a class method or even a C function that lazily creates the array. For example, here's a class method that does what you want:
+ (NSArray *)frequencyChoices
{
static NSArray *choices;
if (choices == nil)
{
choices = [[NSArray alloc] initWithObjects:
#"Daily", #"Weekly", #"Monthly", nil];
}
return choices;
}
Writing the same functionality as a C function makes it even more general:
NSArray *frequencyChoices(void)
{
static NSArray *choices;
if (choices == nil)
{
choices = [[NSArray alloc] initWithObjects:
#"Daily", #"Weekly", #"Monthly", nil];
}
return choices;
}
The advantage of a class method though, is that you could override it in a subclass if that might ever prove handy.
If your application is simple, consider the Singleton model where the data you are accessing are accessible through the global instance of the singleton.
link text
Rather than using a Singleton approach, consider determining which object in your app's object hierarchy should own this array, and then pass that reference down to where it's needed (see: dependency injection).
You could save the array as a plist in your project and load it in each place where it's needed with
NSArray *arrayDisplay = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"myArrayName" ofType:#"plist"]];
This will work as long as you do not need to change the values in both place while the program is actually running.
If you don't mind global variables, you can instantiate them at load time:
#interface FooClass : ... {
...
}
static NSArray * FooClass_timescale;
#end
#implementation FooClass
+(void)load {
FooClass_timescale = [[NSArray alloc] initWithObjects:#"Daily", #"Weekly", #"Monthly", nil];
}
#end
I prefer doing this when there are a pile of things I want to instantiate (e.g. colours for a theme/skin/brand/whatever), since it's shorter than writing a function to return them. Of course, it's possible to accidentally modify the global variable, but I've never managed this (usually I just forget to retain).

iPhone - Merge keys in a NSArray (Objective-C)

I'm having troubles with arrays and keys... I have an array from my database:
NSArray *elementArray = [[[menuArray valueForKey:#"meals"] valueForKey:#"recipe"] valueForKey:#"elements"]
The problem here is that I would like all my elements of all my meals of all my menus in an array such that:
[elementArray objectAtIndex:0] = my first element
etc...
In the example above, the elements are separated by the keys.
How can I get that?
Hope it's clear enough...
Thanks
From your code snippet, it is not clear to me exactly how your data is structured, but I think it's analogous to having an NSDictionary (called aDictionary) of NSArray and wanting to combine all the NSArray into one. If this is the case, then:
NSMutableArray *resultArray = [[[NSMutableArray alloc] init] autorelease];
for (id dictionaryKey in aDictionary) {
[resultArray addObjectsFromArray:[aDictionary objectForKey:dictionaryKey]];
}
return [NSArray arrayWithArray:resultArray];
(This code has not been tested.)