I’m trying to create an app (my first) that generates invoices for me. Originally my idea was to have the following classes:
- User (who all of the following application data belongs to)
- Customer (who to bill: Name, CompanyName, BillingAddress,
Phone, etc…) - Task (a line item on the invoice: Name, Description,
HourlyRate, etc…) - Invoice (the final output that is comprised of a Customer and
multiple Tasks)
I thought I could have the user select “Add new customer”, which would create a Customer object and then store that object into a customer array. Same thing with “Add a new task”, which would create a Task object and add it to a task array. I would then be able to create an Invoice object that points to a certain value in the customer array and multiple tasks in the tasks array.
The problem I am running into is that I don’t know how to create a new object each time someone presses “Add New Customer” or “Add a new task”. I’ve tried doing something like this:
Customer *customer = [[Customer alloc] init];
[customer setName:@"John Doe"];
[customer setCompanyName:@"John's Swimming Pools"];
[user1 addCustomer:customer];
[customer setName:@"Jane Smith"];
[customer setCompanyName:@"Cupcakes by Jane"];
[user1 addCustomer:customer];
for (int i = 0; i < [[user1 customers] count]; i++) {
NSLog(@"%@",[[[user1 customers] objectAtIndex:i] name]);
}
I realize this doesn’t work because the pointer to customer is being overwritten with Jane, so when the array is printed both values in it say “Jane Smith”.
How can I create a new pointer to an object every time the user decides to add a customer/task? Or am I going about this all wrong and should be using arrays for everything instead of classes? I feel like this is very basic OOP and I am struggling to wrap my head around it. Any help would be greatly appreciated, thank you!
If each time some one presses and only one customer is added then why you are adding it twice in the same place?
A simple factory method for adding a customer could be defined in customer class.
At first declare it in Customer.h like:
Then in .m :
Then in your code when you need to add a customer, just call:
And call it any times you want. Your problem should be solved.
N.B. You must import Customer.h in your class where you call this factory method.