Introduction to Core Data: Your First Step to Persistent Data. Editor’s note: After we published the, some readers asked about Core Data and how we can use it to save persistent information. This week, we work with, an independent iOS developer, to give you an introduction of Core Data and work with you to build a sample app using Core Data. This tutorial talks about persistence on iPhone (or other iOS devices). What I mean by persistence is to make data that’s in your apps stay around between application launches. Persistence lets users store persistent data and also retrieve it, so that users don’t have to reenter all their data each time they use their applications.
There are multiple ways to store data in iOS devices but most of them aren’t good enough to store a complicated data. They are usually used to save settings or to preload some data such as “Property List” and “Archiving Objects”. So that’s why we’ll go through Core Data to see how you can utilize it to manage data in database.
The focus of the tutorial is to provide a practical introduction of Core Data framework. I expect you’ve already gone through our tutorials about.
I will not give in-depth explanation about how to create view controller in Storyboard but you can always refer to the to gain better understanding. Core Data is not a Database When we talk about persistent data, people probably think of database. If you are familiar with Oracle or MySQL, you know that relational database stores data in the form of table, row and column, and it usually facilitates access through what-so-called SQL query. However, don’t mix up Core Data with database. Though database is the default persistent store for Core Data on iPhone, Core Data is not a relational database. It is actually a framework that lets developers store (or retrieve) data in database in an object-oriented way.
With Core Data, you can easily map the objects in your apps to the table records in the database without even knowing any SQL. To illustrate the concept, let’s begin and create your first app using Core Data. This app is called My Store. It is a very simple app that stores all devices you have by collecting the name, version, company.
Set up Xcode Project Options – Remember to select Use Core Data Core Data Stack Before we start working on the project, you first have to understand the Core Data Stack: Managed Object Model – It describes the schema that you use in the app. If you have a database background, think of this as the database schema. However, the schema is represented by a collection of objects (also known as entities). In Xcode, the Managed Object Model is defined in a file with the extension. You can use the visual editor to define the entities and their attributes, as well as, relationships. Persistent Store Coordinator – SQLite is the default persistent store in iOS.
However, Core Data allows developers to setup multiple stores containing different entities. The Persistent Store Coordinator is the party responsible to manage different persistent object stores and save the objects to the stores. Forget about it you don’t understand what it is.
You’ll not interact with Persistent Store Coordinator directly when using Core Data. Managed Object Context – Think of it as a “scratch pad” containing objects that interacts with data in persistent store. Its job is to manage objects created and returned using Core Data. Among the components in the Core Data Stack, the Managed Object Context is the one you’ll work with for most of the time.
In general, whenever you need to fetch and save objects in persistent store, the context is the first component you’ll talk to. The below illustration can probably give you a better idea about the Core Data Stack. Note: While we encourage you to build the user interface, you can also skip the procedures. The template already comes with the Storyboard and set up all the view controller classes for you.
This gives you a good starting point to work on Core Data. If you use the template, you can skip this section and go directly to the “Diving Core Data” section. The next thing we need to do is to create the Storyboard that defines the views of our app. Navigate to File New New File and choose Storyboard in the User Interface template.
Click next and select the iPhone device family, click create. Creating the Table View Controller Drag a View Controller to the Storyboard and add a Navigation Bar to the top of the screen. Next, drag two buttons into the navigation bar.
Name one as “Cancel” and the other one as “Save”. In the content view, add three text fields and name the placeholder attributes as “Name”, “Version” and “Company”. This detail view will be shown when user taps the “+” button in the table view controller. So finally, press and hold the Control key, click the “+” button and drag towards the detail view controller. Select “Modal” as the Segue action to connect the table view controller and detail view controller. ( IBAction ) save: ( id ) sender; Diving into Core Data With the user interface, it’s time to go into the details of Core Data. Apparently, there are a couple of areas we have to implement:.
Save device information in the Detail View Controller. Fetch device information from persistent store (i.e. SQLite database) and populate the data into Table View Controller We’ll look into the implementation one by one. Saving Device Information First, we need to implement the DeviceDetailViewController to let user add the devices to the database. Open up the DeviceDetailViewController.m file and add the following code after @implementation DeviceDetailViewController. When user taps the “Cancel” button, we expect the app to close the detail view controller. Line 2 of the above code invokes the dismissViewControllerAnimated method to dismiss the current view controller with animation.
For the “save” method, we first grab the managed object context. Every object that Core Data stores is inherited from NSManagedObject. So we first create a new instance of NSManagedObject for the “Device” entity that we’ve defined in the object model. NSEntityDescription class provides a method named “insertNewObjectForEntityForName” for developer to create a managed object. Once you created the managed object (i.e. NewDevice), you can set the attributes (name, version, company) using the user input.
Lastly, we call up the “save:” method of the context to save the object into database. You can now hit the Run button to try out your app. Tap the “+” button to bring up the Detail View and save a new device. However, the new device is not yet displayed in the table. Let’s move on to see how you can fetch the device information from database. Fetching Device Information Open DeviceViewController.m, add a “devices” property to it so we can save all the devices received. MyStore App using Core Data What’s Coming Next It’s a lengthy tutorial but we try to elaborate the implementation as detail as possible so everyone can follow.
As you can see, with Core Data, you don’t have to care about SQL to save and retrieve data from database. Everything is done behind the scene. This tutorial kicks off the first part of Core Data series. Later we’ll talk more about object relationship. Lastly, let me end the tutorial with an exercise. Try to complete the app by adding the functions that let user update and delete an existing device by selecting a row in the table view. Hope you enjoy the tutorial and feel to leave us comment.
Update: Check out!
Mineral dust aerosol (dust) is widely recognized as a fundamental component of the climate system and is closely coupled with glacial-interglacial climate oscillations of the Quaternary period. However, the direct impact of dust on the energy balance of the Earth system remains poorly quantified, mainly because of uncertainties in dust radiative properties, which vary greatly over space and time. Here we provide the first direct measurements of the aerosol optical thickness of dust particles windblown to central East Antarctica (Dome C) during the last glacial maximum (LGM) and the Holocene. By applying the Single Particle Extinction and Scattering (SPES) technique and imposing preferential orientation to particles, we derive information on shape from samples of a few thousands of particles. These results highlight that clear shape variations occurring within a few years are hidden to routine measurement techniques.
With this novel measurement method the optical properties of airborne dust can be directly measured from ice core samples, and can be used as input into climate model simulations. Based on simulations with an Earth System Model we suggest an effect of particle non-sphericity on dust aerosol optical depth (AOD) of about 30% compared to spheres, and differences in the order of 10% when considering different combinations of particles shapes.
Dust influences global climate both directly, by changing the radiative properties of the atmosphere through scattering and absorption of solar (shortwave) and terrestrial (longwave) radiation, and indirectly, by impacting on cloud formation and properties. While most modeling studies assume a spherical shape for dust particles, detailed analyses of modern desert dust reveal significant deviations of light scattering from scattering properties of homogeneous spheres, and highlight that the modeling of the light scattering by non-spherical particles is required for both accurate remote sensing and improved modeling of the climate impact of modern aerosols and dust. For past climate conditions, ice cores offer a unique opportunity to study the optical properties of mineral dust aerosol and their role on climate evolution, as they preserve a pristine atmospheric input from the past. The EPICA-Dome C and Vostok Antarctic ice cores provide evidence of the significant increase in ice-age dust deposition flux that is inversely correlated with temperature, global sea level and atmospheric CO 2 concentration over the last 800 kyrs.
Dust could potentially play an important role in glacial-interglacial cycles, but model simulations show that dust can potentially dampen or reinforce glacial–interglacial climate changes depending on its optical parameters. Thus, one of the most important sources of uncertainty in paleo-climate studies is related to the poor knowledge of dust optical properties and the way they can change under different climate conditions and within a given climate period. Optical characterization of dust in ice cores is challenging because (1) the dust concentration is extremely low, especially in interglacial ice, (2) sample availability is limited if a good time resolution is desired, and (3) the particle size distribution is broad (sample polydispersity), which generally reduces size resolution. The extremely low number of particles in ice core samples limits the application of traditional light scattering approaches, except for single-particle detectors.
Optical particle counters (OPC) and single particle optical sizing (SPOS, single particle obscuration sensor) are effective. The former method measures the size from the scattering cross section, the latter from extinction (scattering plus absorption,) and it has been systematically applied in continuous flow systems for high-resolution analyses of ice cores.
In both cases particle size is obtained from one parameter, thus any other feature affecting light scattering remains unknown. In particular, composition, internal structure, shape and orientation of each grain can affect the measurements, introducing errors in size estimates. In addition to optical methods, the Coulter Counter technique, based on electrical impedance, is widely applied in ice core measurements, mostly because of its accurate size measurement and sensitivity to low concentration levels. The Coulter Counter technique gives volume-size distributions of equivalent spherical particles without a priori assumptions on shape and composition. However, results from Coulter Counter and optical extinction methods often disagree, primarily because key information is missing about single particles, such as particle shape, orientation, refractive index. In this work we applied, for the first time, the Single Particle Extinction and Scattering (SPES) method, to East Antarctic ice core samples from the LGM and the Holocene. We derive information about dust particle shapes (in particular the aspect ratio), which is critical to determine the intrinsic optical properties of dust, which are needed by radiative transfer models.
The SPES data, here obtained at a wavelength λ = 635 nm, consist of two terms: the extinction coefficients ( C ext), generally plotted on the abscissa (μm 2), and optical thickness (ρ, adimensional), plotted on the ordinate. Optical thickness is defined as ρ = k (n/n 0 − 1), where k = 2 π/λ (λ is the wavelength of light), is the geometrical average thickness over the geometrical cross section in the transverse plane with respect to the incoming light, n and n 0 are, respectively, the refractive indices of the particle and of the surrounding medium. The SPES method is thus able to uniquely constrain dust optical properties, which is not possible with measurements from Coulter Counter or optical extinction techniques. Optical Properties of Glacial and Holocene Dust From Dome C The last climatic cycle provides a logical first target for the analysis of the paleodust optical properties from central East Antarctica, since glacial and Holocene dust size, concentration in ice, depositional flux, and sources are relatively well known,. On a global scale, LGM dust deposition rates were 2–4 times higher than during the Holocene.
In central Antarctica the observed ratios were up to 25, mostly because of enhanced dust emission from southern South American sources and changes in dust atmospheric lifetime. In this work, we analyzed ice sections from the “ old Dome C” ice core drilled in 1977–78 about 50 km away from the site where some years later the EPICA Dome C drilling was deployed. We analyzed samples (see Methods) from both the Holocene (H1 group 4.2 ka BP, H2 group 7.4 ka BP) and the LGM (G1 group 22.3 ka BP, G2 group 24.8 ka BP).
Coulter Counter and SPES measurements were performed on two aliquots of the same sample, in order to make results fully comparable. In order to highlight the information achievable from the SPES method, we present a subset of samples displaying very similar Coulter Counter size distribution, but very different optical properties (determined by SPES), which appreciably affect the propagation of light in the atmosphere. In we show SPES results obtained from two adjacent samples (DC-617-3 and DC-617-4) from the last glacial maximum (G1 group), spanning a time period of less than 15 years overall. Depict the SPES plots obtained from two Holocene samples from the H2 group (DC-280-1 and DC-280-3), covering a time period of less than 10 years.
Data ( C ext versus ρ) are presented as 2D histograms, the yellow-blue color scale indicating the number of particles in each 2D bin (linear scale, yellow = 0) normalized to the maximum value of each plot (blue). Continuous lines represent the SPES results expected for spheres with a refractive index n = 1.55 + 0 i (black) and n = 1.50 + 0 i (red), very close to the indices of the minerals found in the Dome C ice core. SPES optical data from the old Dome C ice core represented as the adimensional optical thickness (ρ) versus extinction coefficient (C ext) (μm 2). Data are 2D histograms, the color scale indicating the number of particles (yellow = 0, blue = 1, linear scale) in each 2D bin, normalized to the maximum value of each plot. In a and b two adjacent glacial samples (LGM, ca. 22300 yrs B.P.) are considered (DC-617-3 and DC-617-4 respectively); in c and d we show two Holocene samples (ca. 7430–7440 yrs B.P.; DC-280-1 and DC-280-3).
Time interval is 2 μm 2 (1.1 μm in spherical equivalent diameter). Nevertheless, the whole set of data is useful for two reasons: 1) it can be directly compared to the traditional extinction measurements; 2) a very precise sizing, based upon a method which incorporates the shape effects, can be obtained by extrapolating the properties of the particles from the upper size region to the whole range. We derive information about particle shape by combining the results of numerical simulations performed for different aspect ratios, as briefly described in the. Notice that a uniform distribution of the aspect ratio for different sizes can be reasonably assumed here, as discussed in, for desert dust. Shows Coulter Counter volume-size distributions of samples, performed according to the protocol adopted for the EPICA Dome C ice core, and size distributions obtained from the SPES extinction data (red).
These latter correspond to data which could be obtained with a traditional extinction instrument, interpreting the extinction cross sections as due to spherical particles of a given material. A specific algorithm was applied to convert extinction data into volume distributions (see Methods), to make this results as consistent as possible to earlier studies. We considered the sample DC-280-3 as reference, and we used the same procedure for all the data set. Still, small differences can be observed between DC-617-3 and DC-617-4 ( vs. ), as well as between DC-280-1 and DC-280-3 ( vs. We interpret these discrepancies as related to different C ext values for different particle shapes, for a given particle volume. Coulter counter volume-size distributions (black) for samples shown in and volume-size distributions obtained from SPES C ext data (red).
The SPES size range is limited between 0.5 and 3 μm (sphere-equivalent diameter). In order to interpret SPES data we rely upon a large number of numerical simulations of the radiation scattered by known, non-spherical particles with given composition, sizes, shapes, aspect ratios and orientations. Almost 10 6 particles have been simulated and the results organized in such a way to build a benchmark of numerical results in terms of and C ext. This approach is well described elsewhere, and some examples are reported in the.
Show the typical populations obtained for oblate and prolate particles, respectively. In the simultaneous presence of oblate and prolate particles is evident from the superposition of two optical thickness distributions with different widths, and we can estimate a population of 75% ± 10% oblates and 25% ± 10% prolates. In we have evidence of a mixture of prolate and isometric particles, as evident from the bimodal distribution of Log ρ, in which one of the modes is close to the sphere lines. Here a population of 60% ± 10% prolates and 40% ± 10% spheres is estimated. On the basis of the numerical simulations it is possible to extract information about the aspect ratio of dust particles.
The modes of the aspect ratio distributions are 0.2 ± 0.1 (oblates, ) and 3.5 ± 1.3 (prolates ). Although the method is based upon optical measurements, strictly speaking we retrieve the geometric aspect ratio (methods).
No independent direct check is possible on these results, but independent SPES measurements have been performed on calcined standard reference materials of known composition for which precise numerical simulations for the expected shapes are possible. These results support our interpretation of ice core data. In we show the chronostratigraphic position of the groups of samples selected for this study from the old Dome C ice core with respect to the EPICA-Dome C stable isotope (paleo-temperature proxy ) and dust flux records. In we show the mode and standard deviation of the optical thickness distributions obtained for 2 μm 2. ( a) EPICA-Dome C stable isotope profile (Jouzel et al.; black line) and dust flux records from Lambert et al., and Delmonte et al. 2008 (Coulter Counter in grey, and Abacus in red); vertical blue lines mark the average position of the four set of samples (H1, H2, G1, G2) selected for this study from the old Dome C ice core.
( b) Mode (triangles) and standard deviation (circles) of the optical thickness distributions from SPES data. The two values reported for sampleDC-617-4 (solid and open circle), are related to the presence of two populations. Ellipses evidence results obtained from samples discussed in.
Experimental errors are comparable to the size of the symbols. Climate Implications Given the novelty of our approach, which provides access to properties hidden to traditional methods, we will briefly examine and discuss the corresponding effects on the airborne particles. Radiative transfer models embedded in Earth System Models usually calculate the alteration of irradiance fluxes by aerosols in the atmosphere, by combining the simulated mass mixing ratios of specific constituents and their prescribed (size- and wavelength-dependent) intrinsic optical properties (e.g. Mass extinction efficiency (MEE), single scattering albedo (SSA), asymmetry parameter). Those latter can be derived off-line based on information of the particles physical properties assuming a homogeneous composition.
Different sets of values of MEE for airborne particles were derived by numerical simulations of the particles used to interpret the data presented in, taking also into account aspect ratios. Different shapes have been considered (ellipsoids, cylinders, prisms with 3,4,5,6 lateral faces), but negligible differences in the optical properties were observed for a given aspect ratio; in contrast, important changes occur upon changing the aspect ratios.
We thus considered prisms with aspect ratios in the range 3–4 for prolate particles and 0.25–0.35 for oblate particles. No surface roughness has been included in our simulations. For comparison we also generated a reference data set for spherical particles with the same volume-equivalent size distribution, thus mimicking the Coulter Counter measurements. We consider four sets of optical properties , obtained from samples that show similar particle size distributions when measured with a Coulter Counter. This will allow us to explore and quantify the space of potential variability in the climate impacts of changing optical properties, which is hidden when not considering variability in particles shapes.
Effects of the particle size distributions and shapes on dust AOD evaluated as described in the text. ( a) Size-resolved (on the CESM size bins, identified by the grey solid lines on the x-axis) sets of MEE (um 2) from the SPES analyses (solid lines), and as used in the CESM Albani et al. (dotted line). ( b) Normalized particle size distributions (on the CESM size bins) from the EPICA Dome C (EDC) core for the LGM and Holocene periods (average distributions) Delmonte et al.
( c) Atmospheric column extinction (AOD) due to dust, assuming (1) the dust mixing ratio and size distributions from a CESM simulation of the LGM climate (C4fn-lgm) Albani et al. , tuned to match dust deposition and size distributions at EDC, and (2) the MEE determined from SPES analyses of sample DC-617-3&4, assuming spherical particles.
( d) LGM/current climate ratio of dust AOD, calculated assuming the dust mixing ratio and size distributions from the CESM simulations (C4fn & C4fn-lgm) Albani et al. , tuned to match dust deposition and size distributions at EDC, and the MEE determined from SPES analyses of sample DC-617-3&4, assuming spherical particles. ( e) Dust AOD anomaly for changes in dust size distributions alone (comparing the LGM vs current size distributions), assuming the dust load of the tuned current climate simulation of d) and MEE of spheres (DC-617-3&4). ( f) Anomaly (expressed as fraction) between the dust AOD based on MEE assuming prolate prisms (DC-280-3) with respect to that of spheres, assuming the same dust size distributions for current climate as in ( d).
( g) Same as ( f), comparing the cases with prolate (DC-280-3) and oblate (DC-617-3) prisms. ( h) Same as ( f), comparing the cases with prolate (DC-280-3) prisms and a mixture (1:0.6) of prolate prisms and isometric particles (DC-280-1). Numbers in the bottom left corner of panels c-f represent the average value of the respective fields for latitudes. Methods In this work we apply the novel single particle extinction and scattering method (SPES); it provides two independent parameters for each detected particle and is particularly efficient for very diluted and polydisperse samples such as Antarctic ice. This approach is based upon combined and simultaneous measurements of the power reduction of a laser beam in presence of the particle (i.e.
Extinction by very definition) and the interference between the intense transmitted beam and the much fainter forward scattered wave (i.e. In such a way it is possible to access the amplitude and phase of the scattered wave (i.e. The real and imaginary parts of the complex field amplitude, see ). From SPES data each particle is thus characterized by the extinction cross section, C ext, and the optical thickness ρ = k (n/n 0 − 1), where k = 2 π/λ (λ is the wavelength of light), is the geometrical average thickness over the geometrical cross section in the transverse plane with respect to the incoming light, n and n 0 are respectively the refractive indices of the particle and of the surrounding medium. By imposing preferential orientations to the particles through shear of meltwater sample flowing into the scattering volume, we are able to evidence non-spherical particles (oblate and prolate) and to obtain a good estimate of the average aspect ratio from the measurement of a few thousands of particles. A benchmark of expected SPES data has been obtained from accurate numerical simulations of about 10 6 representative particles by means of the A-DDA simulation code. We have simulated the scattered fields from single particles with diameters from 0.5 to 5 μm, refractive index from n = 1.45 to 1.60, aspect ratios between 0.1 to 1 (oblate) and from 1 to 8 (prolate).
For practical reasons we define the aspect ratio as the ratio between the smaller dimension and that perpendicular to it for oblate particles, and the inverse for prolates. It is thus possible to build look up tables for inferring the distribution of the aspect ratios, and therefore to achieve an accurate sizing based upon the actual shapes. Notice that, despite the optical approach, in such a way SPES partially overcomes the typical limitation of optical methods, namely to give the so called “optical diameter” and “optical aspect ratio”.
Indeed, just by recovering the aspect ratio from the geometrical characteristics of the particles through proper numerical simulations, we directly provide an estimate of the geometrical aspect ratio. As a direct consequence, also the size is estimated on the basis of the true shapes, instead of the common optical size which is the diameter of a sphere having the measured cross section. These results are of great importance when extracting optical properties of the airborne particles, as discussed here. It is impossible in general to assign one size value to a given C ext, as it is evident in the for the oblate particles case.
For prolates, conversely, it is easier to recover particle size thanks to a one-to-one relationship between size and C ext (see, DC-280-3), as explained in the. Therefore, by following the same procedure adopted with traditional SPOS technique, we have recovered the size distribution from our extinction measurements on sample DC-280-3 (, red) by assuming spherical shapes and fitting a free parameter ultimately related to the apparent refractive index, or to the optical thickness itself, to reproduce the corresponding Coulter measurements (, black).
The same conversion with the same parameter has been applied to the other samples. Discrepancies among Coulter and extinction in can be reasonably attributed to shape effects. The simulated dust mixing ratios, which were used as a basis for the estimation of the effects on atmospheric dust AOD of the newly retrieved optical properties, were performed with the Community Earth System Model and extensively validated for different climate conditions (including present-day and the LGM) against climate and dust observations, (see ). For each horizontal grid cell in the model: where b represents each of the four size bins in the CESM dust model (spanning 0.1–10 μm in diameter), MEE b,VIS is the size-dependent MEE in the visible wavelengths spectral band ( i.e. 550 nm), and DL b is the column dust loading in each size class.
Author Contributions M.A.C.P., S.A., B.D. Conceived this study. Designed and realized the SPES instrument, analyzed and interpreted data; S.A. Studied the climate implications; B.D.
Contributed to the measurements and the data interpretation; S.V. Did the measurements and developed the data interpretation schemes; T.S. Realized the instrument and gave support to the data interpretation; B.P.
Gave support to the instrumental device; G.B. Performed the Coulter measurements and interpreted data; N.M. Contributed to the general overview of the work.