Note that there are some explanatory texts on larger screens.

plurals
  1. POHow would you dynamically create class instances in objective c
    text
    copied!<p>I'm not sure if I am using wrong vocabulary to search for this but I'm not able to find anything that seems to relate to what i'm trying to do.</p> <p>I have a class that I have made for entering expenses. I has Name, amount, and dueDate member variables. I am using command line tool to create this class and test it out. What my question is is how would i go about creating an object from my class as the user needs to add an expense. This is what I have done to make it work. I don't like it. </p> <p>My while loop creates a new instance of my class then gets the user input, sets the member variables of the expense class, and lastly adds the object to an array for latter use.</p> <p>Everything works i just don't like that every object basically has the same name. I would have liked to create the name of the object from the name the user entered but having users enter names of classes is not good i have found out. So any suggestions please. And I am fairly new to programming so the code is probably very ruff.</p> <pre><code> NSMutableArray *myExpenses = [[NSMutableArray alloc] init]; while (enterMore == 1) { Expense *anExpense = [[Expense alloc]init]; NSLog(@"Enter an expense:\n\nName: "); scanf("%s", expenseName); billName = [NSString stringWithUTF8String: expenseName]; anExpense.name = billName; NSLog(@"\nEnter the amount of the expense: "); scanf("%lf", &amp;expenseAmount); anExpense.amount = expenseAmount; NSLog(@"\nEnter the day of the month the expense is due: "); scanf("%d", &amp;dateDue); anExpense.dayOfMonthDue = dateDue; [myExpenses addObject:anExpense]; NSLog(@"Enter 1 to enter more expenses anything else to quite: "); scanf("%d", &amp;enterMore); } for (int i = 0; i &lt; [myExpenses count]; i++) { NSLog(@"%@", [[myExpenses objectAtIndex:i] name]); NSLog(@"%f", [[myExpenses objectAtIndex:i] amount]); NSLog(@"%d", [[myExpenses objectAtIndex:i] dayOfMonthDue]); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload