saving a to-many-relationship - core-data

I'm starting to learn and practice some CoreData, with no programming experience.
After searching in Web, looking for Apple samples and reading some books, I´m still stucked in one point.
I have two entities (Expenses and Month) with reciprocal relationships called "monthsOfExpense" and "expensesOfmonth" and I'm showing in a tableView the expenses of a single month.
My problem is to insert new expenses and save them: I've a view to insert new expenses where the user can insert the name of Expense, the value and the months that expense is valid (associated with the monthsOfExpense relationship, i hope).
I'm ok saving the name and the value of Expense entity, taking the string and NSDecimal number from the textFields.
My problem is how to associate that expense to a particular or several months? How can I save a textField.text as a relationship, indicating to what month an Expense belongs?
I'm starting with a textField where the user can insert a month, assuming that an Expense is valid for one month only (for learning purposes and simplification).
My idea is to allow the user to select several months (using maybe another tableView with selectable months) and association of an Expense to different months.
I know that a relationship comes as a NSSet, but I'm not being competent to save the attributes and the relationship from a View, at the same time.
Hope was cleared and many thanks in advance for trying to help.

OK. In Core data, you define your "Expense" entity, create a relationship to "Month" entity. Now create class files for these 2 entities. Then you use it by
Expense *expense1 = [NSEntityDescription insertNewObjectForEntityName:#"Expense" ....
Month *month1 = [context executeFetchRequest:......];
expense1.month = month1;
...
[context save];

In your situation, you can predefine 12 "Month" objects, giving the month name as the text property.
Then you can lookup these month objects using NSFetchRequest. Add the relevant month objects to your expense using
[expense addMonthObject:month]
Then save your managed object context.

You message the managed object for its mutableSetValueForKey:RelationshipKey,
then you add the to-many managed objects to that set. CoreData completes the other half of the relationship data.

Related

How to handle a Value Object referencing an Entity?

I have just started to look into DDD, and is trying to look into some scenarios.
I have a Product (Entity) with a ProductName (Value Object) and a ProductPrice (Value Object). The Product Price then have an amount (decimal) and a Currency.
My issue is regarding the Currency. First I designed this as a Value Object, but it should be possible to add new Currencies to the system, and it should also be possible to list them in some kind of GUI. In other words it seems like I need a repository for Currencies. In my mind this means that Currency should be designed as an Entity.
But, now I have a Value Object (Product Price) referencing an entity (Currency). How should this be handled? My guess (I am not sure) is that I remove the reference to the currency entity inside the Product Price, and instead adds the Id of the Currency (USD, EUR etc). The Currency then becomes its own aggregate.
Is this a valid and preferred design in DDD, or should this be done in some other way?
In the original DDD book, Evans did discuss the possibility of having values that can reference entities. (Chapter 5: "VALUE OBJECTS can even reference ENTITIES")
I think everybody, by and large, has abandoned that practice. Immutability is too powerful an idea. Values will normally only reference other values. Instead of referencing a entity, we include the entity identifier.
So the usual solution would be that you model the currency code as a value, and store (copies of) that value in your Price value.
The Currency then becomes its own aggregate.
I would not expect this to happen. How does a currency change over time?
What I think you will find is that currency is fairly static: the thing that changes over time is the CurrencyExchange -- which currencies are currently listed? what is the exchange rate today? What was the exchange rate two years ago? Which political units prefer this currency as of Thursday?
Currencies are closer in nature to units of measure: feet, inches, meters, pounds, liters seconds. Meters are a unit of measure in the dimension of length; currency is a unit of measure in the dimension of "money".
how do you handle that new currencies can be added to the system, and how can you select between currencies in the GUI?
There are two possible answers to that.
If your domain is the authority for which currencies are active in the system, then the currency registry/currency exchange should be a first class entity in your domain model, and manages the process of change to the listed currencies.
If your domain is not the authority, then you just cache a copy of the information you get from the authority. Caches are typically CRUD (PUT, GET, DELETE, maybe PATCH).

Tableau Calculated Field using FIXED

I have a database in Tableau from an Excel file. Every row in the database is one ticket (assigned to an Id of a customer) for a different theme park across two years.
The structure is like the following:
Every Id can buy tickets for different parks (or same park several times), also in different years.
What I am not able to do is flagging those customers who have been in the same park in two different years (in the example, customer 004 has been to the park a in 2016 and 2017).
How do I create this calculated field in Tableau?
(I managed to solve this in Excel with a sumproduct fucntion, but the database has more than 500k rows and after a while it crashes / plus I want to use a calculated field in case I update the excel file with a new park or a new year)
Ideally, the structure of the output I thought should be like the following (but I am open to different views, as long I get to the result): flag with 1 those customers who have visited the same park in two different years.
Create a calculated field called customer_park_years =
{ fixed [Customerid], [Park] : countd([year]) }
You can use that on the filter shelf to only include data for customer_park_years >= 2
Then you will be able to visualize only the data related to those customers visiting specific parks that they visited in multiple years. If you also want to then look at their behavior at other parks, you'll have to adjust your approach instead of just simply filtering out the other data. Changes depend on the details of your question.
But to answer your specific question, this should be an easy way to go.
Note that countd() can be slow for very large data sets, but it makes answering questions without reshaping your data easy, so its often a good tradeoff.
Try this !
IFNULL(str({fixed [Customerid],[Park]:IF sum(1)>1 then 1 ELSE 0 END}),'0')

Creating relationship between two different columns- a relationship that effects other values

I'm going to try and make this as least confusing as possible, I apologize in advance if my attempt is a failure.
I work in education and am trying to create a predictive analysis document that will tell us how many class sections we will need to offer in a given semester.
I pulled data from the past five years and consolidated it into a pivot chart. I set the pivot chart to combine all courses with a common Subject, Course Title and Catalog Number (See image below for more detail), and output 3 different columns of values based on what we need.
The problem I am facing now is with curriculum changes throughout the years. There are some courses within the list that are no longer being offered and a new course with a new Course Title, Subject and Catalog Number that can now be substituted for the previously needed course. Since the data has been pulled into one pivot chart, both the old curriculum courses and the new curriculum courses are in one list.
I would like to somehow create a relationship between the old curriculum courses and the new curriculum courses. If possible I would like the names of the courses to remain separate, but the values of the old and new to be averaged out together in their respective rows.
In a new page, I plan on putting an easy to use form where the user can select a course subject and name, enter in some other necessary data and the document will output the amount of course sections needed.
Does anyone know of a way to make a relationship between two cells and have other cells effected by this relationship?
Thanks so much!
Mike
enter image description here

Breaking up a Core Data Date Attribute - Good idea?

I am learning Core Data, and I have a project up and running that stores, creates, retrieves, updates, and deletes entities just fine. I am loving using Core Data so far.
I have a simple entity that has 5 attributes. One of them is a date. I call it dateCreated. I am using a TabBar in my app and I want to be able to sort things on different screens by Year and Month, and Month details. I have a couple questions about what is good practice and what is good for performance sake.
So ideally I want my Collection View to be sectioned by Year, and each cell containing a month that takes them to that months table. Currently in one of my tabs have a UITableView that loads user created data but I haven't broken it up by Year and Month yet. Meaning they can just keep putting in dates and other info and the one table just keeps getting larger. I would love to use the Date Attribute my - dateCreated attribute to break the table into multiple tables for each month in my Collection View. It seems like all the data is in place to minipulate and display it anyway I want, but I am not sure if it is the best way to go, or even if it is the standard practice when using Core Data. I would think I could use the same table to load the data based on what year and month it is. Instead of making multiple tables of months.
My questions as long winded as they are: Should I create more Date attributes or use the dateCreated that is displayed in my TableView using a formatter to show it as "Jul, 31 2013". In other words can I break up the user created data based off of my dateCreated attribute alone.
Second. I understand how to "fetch" data from the Core Data stack and get it in the TableView using NSFetchedResutsController, but what if I want to display certain attributes from an entity in a screen that doesn't have contain a table view. Should I still use NSFetchedResultsController, or should I be using something else? The Apple Docs on Fetching Data shows how to fetch specific attributes from the entity to be displayed but it seems like so much code for something so simple that I think I have looked in the wrong section.
Okay I understand this sounds a bit confusing so I am wanting to know if I should use my dateCreated attribute to break up the data, or create more Date attributes one for year, one for month and keep the one for dateCreated and sort it that way. Also if I just want to display certain attributes data without a table on screen should I still be using NSFetchedResultsController?
Thanks for all your help if you provide any. I am having a great time learning Core Data. It is really powerful.
You might want to adjust your predicate for the fetching to something like:
NSDate *startDate = ....;
NSTimeInterval length;
[[NSCalendar currentCalendar] rangeOfUnit:NSMinuteCalendarUnit
startDate:&startDate
interval:&length
forDate:startDate];
NSDate *endDate = [startDate dateByAddingTimeInterval:length];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(eDate >= %#) AND (eDate < %#)", startDate, endDate];

How to Sort View control by Lookup column

I have two forms that are related and I would to combine them in a view control. Not that difficult. This is for a "1 to Many" type scenario.
Say I have a customer view with the columns customerID and Customer Name. Then I have a view showing the "many" documents that has the columns masterCustomerID, orderNumber, orderDate.
On the XPage I create a view control of the many documents and add the columns masterCustomerID, orderNumber, orderDate. Then I add a column in the front to do a DbLookup to pull in the actual name of the customer. Nothing too fancy really.
My question is, in this situation, where the lookup column is the FIRST column. What are the strategies to sort the view column by that column. By default it would sort by the Key Value in the order view which is likely different then the Name values.
I'm not averse to using repeat controls if that would be easier.
My first thought would be to employ TreeMaps somehow, but I don't know if that's practical in the event that there might be a LOT of documents. Maybe there's something I'm missing...
Any advice would be appreciated. Thanks
Use view with (Customer name, Customer ID) structure as main view. Then based on Customer ID populate other columns by lookup from view with structure (Customer ID, Order ID, Order date). Hence it is 1:N relationship, you can't use single view component, but two nested - repeat inside view column would do.
I hope you are aware of performance impact (orders looked up for every customer row), so don't try to show too many customers at once.

Resources