WWDC2004 Session 418
Transcript
Kind: captions
Language: en
okay good afternoon welcome to session
418 introduction to core data my name is
andreas vantika and i'm the senior
manager for core data and web objects
and core data is a new framework that we
added under the cocoa umbrella and it
continues an initiative we started last
year with cocoa bindings
that's the initiative to bring you and
your applications more functionality for
adding significantly less code like
bindings core data addresses fits gap in
the cocoa functionality core data is
concerned with fine-grained management
of data objects in this space it solves
a number of very difficult problems and
I actually believe that it will have a
much stronger impact on your application
development development and even cocoa
bindings head when I talk about data
objects in this session I really mean
the objects that you refer to as the
model objects in the model view
controller sense but I'm going to use
the term model in a different context
throughout the session so I decided to
stick the data objects also I'd like to
distinguish core data clearly from the
new metadata API the new spotlight API
core data is about the inside of your
data ups of your data files about your
own applications documents and metadata
it really is about the surface about the
outside of those files that you want to
export to the file system and to the
Search API so one thing that sentance
core data is a model driven object graph
management and persistency framework
that's certainly a mouthful but what
does it actually mean it means that if
code data instead of writing a lot of
code you create a description of your
data objects you create a description in
Xcode and that description is called the
model of your application and the model
is what's used by core data to manage
pretty much most aspects of your data
objects for you and it's do that both in
memory and on disk that means that you
are actually freed up to focus entirely
on the application specific problem
domain instead of having to focus on
developing infrastructure for your
application so what can we do with the
model I think the most immediate benefit
to many of you will probably be that you
can provide you with automatic
and ruin redo in your applications so
with core data no more worrying about
that and as undo manager we also provide
you with scalable object lifecycle
management that means that we actually
only keep the pieces of your data in
memory that is currently needed and we
leave the rest on disk so it skates very
very if you automatically synchronize to
user interface you do that - cocoa
bindings but we added a few pieces to
bindings to make the situation even
smoother and core data also helps you be
ready to manage the consistency and
correctness of your data and all you
have to do is specify a bunch of rules
in the model that tells the tale core
data how to validate user input and how
to maintain relationships or references
of your objects to each other the other
thing we can do is we can ultimately
read and write your objects to the disk
and we're going to support three
different file formats and this first
release SQL databases XML files and
binary archive files SQL files are
implemented on top of SQLite which is a
very nice lightweight embedded SQL
database it's an open source project and
SQL databases will usually give you the
best scalability if you have large sets
of data and that's the case because with
SQL databases we can update your files
incremental e we don't have to write the
entire file if just one object changes
everything is incremented and a lot of
the data can stay on the disk
the only fetch them into memory even
needed XML files have the huge advantage
today a human readable and they easily
consumed by other applications if you
need to exchange data but they won't
give you the same performance one other
advantage of XML files is that they are
written atomically so if you are in the
typical code document context but you
want to write the files atomically if
you if you save the next file it's
actually a very good fit and binary
files I kind of in the middle they are
probably good compromise they don't give
you quite the performance of SQL
databases and they don't scale to the
very large data sets but they written
atomically and they are reasonably fast
now what's important for this first
release is that when you use core data
we will take ownership of the file
format of the file schemas so in the one
hand that's great because you don't even
have to worry about trading tables in
the SQL database or creating the schema
for
on the other hand you will lose detailed
control of your five formats to give you
some examples of what you could do with
core data I have to just looked at my
doc and the typical applications are
used on a daily basis and none of these
applications disclaimer actually using
core data right now if you're still
building up core data it's really early
but I think it gives you an idea of what
the scope is of things that you can
solve the core data so starting with
Safari the history in bookmark files
that would be a great thing you could do
with core data persons and groups even
the mailbox fights within mayor the
music library of iTunes calendar files
and I care even sketch documents which
have the different graphics in it and
project files and xcode those are all
great candidates for core data
essentially every application that
manages lots of objects they benefit
greatly from using core data the
applications that you will not see that
much of a benefit applications that work
on large blobs of data so for example
TextEdit if it works from the RTF or or
text files and maybe image processing
software won't benefit that much from
core data so why is it good for you most
importantly because it leads you from
having to reinvent the wheel again and
again it again but implementing and when
we do merging your life the life cycle
of your objects input validation it's
all very mundane work that you have to
implement for every application and with
core data it's done for you you save a
lot of time you will have a much faster
development cycle code data also to give
you robustness and flexibility the
choice of different types of data stores
with the different characteristics of
scalability and human readability etc I
think return are very handy for many of
your applications and also very
important correlated will prepare you
way for the future for features we might
add in cocoa now that we have a model we
can interpret that model in many
different ways without you writing it
any line of code so you could envision
us to for example add a transcript
ability to your applications or maybe
automatic rendezvous connectivity so
there are some features we are looking
at in the future that I think you will
be able to pick up automatically if you
start using core data soon these are
actually fine with screenshots from an
actual application we converted over to
core data recently and that application
was already using cocoa bindings so
there was no glue code for the UI layer
and
can see we were still able to save up a
lot of the code and by the way this
application now has more features than
it had before for something now it has
undo and redo so with that I would like
to ask James Dempsey to come up on stage
and give you first demo of core data
Thank You Andres so we're taking a look
at here is an XML document as might be
managed by core data we're gonna put
that away for now
we're gonna jump right in and build a
full-featured document based application
with 0 lines of code using core data
we're gonna use the core data document
based application projects call that
thing demo 1 and with cocoa bindings you
essentially had your data objects able
to be synchronized with user interface
objects through bindings but you still
have to manage those data objects
yourself with core data it's kind of
like the other half of the equation
where those data objects you can model
them core data will help you manage them
and also deal with the persistence so
let's take a little look at the project
and the code that's in there if we take
a look at the classes we have a document
class which is a subclass of NS
persistent document which in turn is a
subclass of NS document and this
subclass adds all of the hooks needed to
interoperate with core data including
persistence let's take a look at the
implementation file and you'll notice a
couple of common NS document methods
here and a few that are missing
ostensibly those that are for writing to
the data writing and reading data so we
don't need these initialization items
either so in essence this is a negative
lines of code demo and we'll next look
at a new resource in the project the
model so a little later in the session
you're going to see how you can create a
model from scratch but to save time
we're going to import that XML file that
I showed you earlier
and Xcode is going to build an entity
relationship diagram based on the
structure of that XML file and if we
take a look we have persons events tasks
as an event management sort of model so
now we have our model let's build our
user interface we'll head into our
document nib file get rid of this and
what we're going to do is option drag in
this case the person entity let me pick
it up here into interface builder
interface builder is going to ask us
whether we want a user interface for one
object handled by an object excuse me an
object controller or many objects
handled by an array controller we're
going to deal with many objects in this
case and you'll notice that a user
interface has been built based on the
properties of the person in the model
and in addition in the RAID controller
has been added to the project let's just
take a look at the bindings of this text
field here take a look at the value and
you'll notice that it's hooked up to the
arrayed controller selection for the
model key path first name it's just a
straight standard cocoa binding in fact
all of the user interface is dealing
with cocoa bindings in that array
controller in the way it has in Panther
so what's the new stuff well if we take
a look at the array controller you'll
notice a couple of additional features
designed to integrate cocoa bindings
with core data the first is instead of
naming a concrete class we have the
choice to pick an entity in this case a
person so that the array controller
knows what type of thing it's dealing
with if we look at the bindings of the
array controller you'll notice a new
binding called managed object context
and the managed object context andreas
will be talking about it later but in
essence it's the object that's providing
and doing a lot of the heavy lifting for
the functionality that we're going to
see in a moment when I build this
application so one entity is kind of
useful but very few applications deal
with one kind of object and one kind of
object alone and core data is actually
very good at dealing with relationships
queen types of objects so a person is
related to many tasks so let's get a
user interface for a task many tasks in
fact let's clean this up a little again
these are just plain old IB things so we
can get rid of them if we want to let's
get rid of some of these let's get that
task field a little bigger so we can
read it get rid of some stuff okay now
let's take a look at that task array
controller we do need to bind its
content so it knows where it's getting
its tasks from we're going to bind that
content to the person array its
selection and within that selection the
tasks of the selected person let's save
our change and let's build our happy
little application here
well that's building let's just take a
look at the types of documents that we
can save to predefined is the binary
archive format the sequel Lite document
format as well as the XML format so our
build has succeeded
let's run hide a bunch of stuff and
here's our application let's open up
that XML file that we had seen earlier
and you'll notice that indeed as I jump
through the items in this table view
everything's updating I'm seeing all of
the tasks that are related it looks like
Andres has the most to do out of
everybody and we have all the common
cocoa bindings sorts of features such as
sorting such as multiple selection and
some new goodies such as filtering so if
I type in some filtering there it'll
filter for me and the UI is
automatically let me there built in a
menu so I can pick particular things
that I want to filter upon now let's
jump on over to our new document and add
some people so let's add Bob Jones let's
add Barry Bonds and let's save
so I'm going to save again these file
formats appear here let's do the sequel
thing call that test we'll save it and
on our desktop is that sequel Lite
document which represents the sequel
database and let's close the doc now
let's open it up again thus proving we
beyond shadow without that it persisted
and there it is I think I forgot to type
in bonds there we go let's make it
persist a there we go what I do I may
have Miskin disconnected that text field
in interface builder my apologies
okay with that let's add a new person
Betty Brant and let's change Bob to
Robert
and let's remove Barry for legal reasons
now you'll notice looking at the
document that the window does know a
change has occurred it is dirty and if
we go to the edit menu we do have undo
so let's undo through this we should get
Barry back Robert should be get back to
Bob and Betty should disappear and of
course redo and if we feel free
and if we quit of course it knows the
dock is dirty in Alaska so if we want to
save we don't want to save okay let me
close up this project I'd like to show
you one more thing beyond that codeless
demo which is that that's a very cocoa
centric demo this application here the
three bears is a carbon application
that's using core data underneath for
its persistence and in fact this is the
XML file that it's writing to let me
just open that up and TextEdit and so
we'll add the baby bear whose height is
very small we'll save and quit and
restart and indeed it has persisted and
then if we get the saved version from
disk you'll notice that that XML
document has updated so let's take a
look at the project and it's an
objective C++ and it's the code here
that is doing a bit of transition
between those objective-c objects from
core data and core foundation types that
carbon would be able to use and so
depending on which flavor you wish you
can use core data with both so thank you
very much and now back to Andres
[Applause]
thank you James now let's talk about
moderates moderates are high level
description of your data objects they
essentially entity-relationship diagrams
of your objects and the model is what's
needed by core data to implement all
these nice features like Unwin redo and
ultimately read and write your data
objects to disk in fact the model is all
that code data needs as you saw on the
dem was before there was no additional
code really necessary to do all this
work one thing that's important though
for you to keep in mind is that you and
your models you would have to spend
quality time together the models need to
be very detailed for us to do a good job
so the more detail you make your models
the better of a job core data can do one
thing that's interesting in this context
is that we decided to separate the five
formats for the models you edit in Xcode
and the models you load at runtime the
reason for that is instead excrement is
additional information if you don't need
at runtime like the layout information
of the diagram and maybe the colors you
chose for the different boxes and if you
didn't want to burn the runtime with
that so while your project is building
you're actually translating the model as
it is written in Xcode and manage an
Xcode into a new file from R that is
then run imported at at runtime models
and essentially consists of two pieces
entities and properties entities to kryb
describe the types of objects and
properties describes the individual
object components the values inside
those objects for each entity you can
specify a class name that is used to
represent that entity at runtime and
specify the class name here we turn out
to be the most important hook for you to
plug in your own application logic
another thing that's interesting about
entities is that they can be organized
in a hierarchy which is actually
independent of the class hierarchy you
use so for example if you have a person
entity you might might have sub entities
like employee and company customer and
you can then map those entities to
either a class hierarchy that is the
same or two classes that have nothing to
do with each other or you can even map
those three entities to the same object
class at runtime
that's actually fairly common
the advantage for you to use entity
inheritance that you model the types of
data that you can for example define
your queries on the abstract entity you
can still search for our persons and
then going back get their customers and
employees so there's there's a lot of
flexibility for you when you work with
your data objects for properties we
support three different types attributes
relationships and fetch properties
attributes represent the simple types of
data in your object like strings numbers
dates and maybe binary data like images
a relationship through present
references of objects to each other and
then we distinguish between two one and
too many relationships the one
relationship is simply a pointer a
reference to another object no too many
relationship is a collection of
references to other objects in this
first release we are going to support
only unordered relationships too many
relationships and the natural
representation for that is action and is
set going forward we are probably going
to add support for ordered relationships
too and those would be represented by NS
race and for NS race we will then also
archive the order of the object in that
array in the data stores relationship
typically come in pairs if you have a
person that points to company there's
usually over also pointed back from the
company to the person those in those
relations are called inverse
relationships and they make your optic
graph very rich actually it makes it
much easier to navigate through your
object graph so you command that you
typically enter the inverse
relationships in your model too and
fetch properties and many ways similar
to relationships but they aren't they
are much more loosely bound you can
pretty much think about them as smart
groups to make it more concrete for you
in an SQL database a relationship will
actually reside in a join that is
enforced in the database a fetch
property is much more of a loose carry
so all these properties the model
contains the beds of information
starting with validation words those are
the kind of mechanical validation words
like the length of a string or maybe the
very expression a string has to match
min and Max values for numbers and dates
those kind of things they also delete
rules for relationships and those delete
rules take all data what to do if an
object is removed from your
Graff typically there's something like a
ripple effect if you remove an object
let's say you have a person object which
has addresses and contact information if
you delete that person you want to get
rid of the other information too and
delete routes allow you to specify that
kind of behavior and their different
choices you can kind of cascade the
delete so that's the ripple effect you
can deny delete depending on the
situation so there's there's a lot of
flexibility in these 2d tools and also
for attributes we store default values
those are simply the values assigned to
your object when it's inserted when they
are inserted so this table summarize the
kind of mapping we do at runtime and
entity essentially maps to a class and
attribute maps to single a simple
instance variable and the relationship
maps to a managed reference or
collection of these references they
appoint us there are some more things in
the model that I want to go over quickly
starting with predefined queries you can
enter pretty much templates for the
common queries you want to do you want
to perform in your application again
it's something like a smart group would
be a good example here and typically you
will specify variable names within those
queries and then substitute concrete
values at runtime so those are very
handy and make it it's actually a huge
convenience for you to specify those
queries in the model up front there also
sometimes we call configurations in the
model a configuration is pretty much a
named group of entities and those
configurations are used in the more
advanced cases when you talk to my to be
data files at the same time each
configuration then maps to one data file
and you can pretty much predefined the
mapping to the different data files in
the model by separating those
configurations and naming them and the
last thing I want to mention is that we
also decided to give you some
flexibility to to customize the model if
you added so called user info
dictionaries to entities and properties
and you can store your own information
that these are pretty much arbitrary key
value pairs you can end in the modeling
tool in the typical use case for that is
actually localization so with that I'd
like to ask Bill I'm gonna turn up on
stage there he is and he will give you a
more detailed demo of the model
[Applause]
good afternoon so what we have on screen
here is the modeling part of Xcode and
as you've seen probably in an earlier
demo this is also used for doing the
class models so I'm going to strict
stick strictly with the entity model and
the stuff that we use to build the
models for core data what we have here
is the graphical view which gives you a
nice overview of how the various
different entities are related to each
other and the attributes that they have
we can then actually go in here and this
is all live so if I wanted to I can come
in here and I can double click on this
and I could edit this I could you know
edit the attributes I can delete them
things like that so we wanted to really
emphasize the ability to graphically
edit your model and work with it and
because we think that being able to
visualize your data structure is
important to helping understand programs
especially when you start getting into
more complex models now this of course
is not actually a rich enough
environment to be able to do full
editing of the model like the validation
rules and property types relationship
rules etc so if you go into the design
menu there is a model browser and once
we bring up the model browser that adds
a set of user interface it's used for
examining your model in depth and for
actually editing it and controlling
everything from the entities through all
the way down to validation rules so we
can come in and we can create new
entities we can obviously delete them we
can also see in the middle table you
have all the properties listed and
actually there's properties and
relationships so we can select these and
you'll see on the right that there's an
inspector area which shows you a lot of
detail now the diagram at the bottom
will actually update in real time based
on what you're entering in the top area
of course so if we choose the attendees
relationship with the destination of
person which will be where is that okay
we've got event there's is there's
attendees right there if I were to
change the rule so the minimum count or
the maximum count was one you'll see
that this arrow right here updated
that's because of course the arrows
indicate the ordinality of the
relationship relationships are allowed
have ordinality x' so that you can say a
car can only have four tires that kind
of thing and upon save and upon
manipulating the objects at runtime the
system will validate that Andreas will
be getting into that in more detail now
there's some other we've learned a lot
about modeling tools we as some of you
might know we've done some things wrong
in the past and hopefully you'll find
this to be a refreshing change so one of
those is that it was tedious and
annoying to have to go through a model
and edit a particular part of an
attribute over and over and over again
so what you can actually do is you can
come in here and you can multiple select
in here and you'll see that the
inspectors over here update to only show
you the items that are relevant to those
things so now I can come in here and I
can like select first name and last name
and I can change the validation rules
for both of those at the same time but
of course oftentimes when you're
modeling stuff you'll have attributes
across many entities that will need to
be changed at the same time so I come in
here and select them all and then I can
sort by entity or I can sort by property
or kind and then I can again select
multiple across multiple entities and
edit them all at once we also have the
fetch request editor so if I come in
here I can build a new fetch request and
on I can then actually edit the
predicate and we give you a graphical
predicate editor so we can come into
here and let's say we all may say this
is confirmed yes and we also want to
make sure that the date is or less than
you know and we can say maybe we want to
add an or here so we can say the date is
greater than
[Music]
I'm obviously making up some random data
there so that's the predicates editor so
that's built into there it also it does
full logical trees you can also
drag-and-drop
let me go ahead and do a little drag and
drop demo so we'll get one of these and
do another hand and then we'll do say
and/or at this level if I wanted to say
oh well this really should be at the top
level Angus dragged it up there and no
restructure itself appropriately and
then of course as andres mentioned there
is the user info here so it's just key
value pairs so we allow you to annotate
your models with whatever you need
thank you so core data can automate
great many things and it can provide
with a lot of infrastructure but of
course we don't know what the actual
problem is that you want to solve in
your application so there's still some
code you have to write yourself and as I
mentioned before you the most important
hook for you for that is to specify your
own data object classes in the model and
the one requirement we have this core
data is that require you to subclass a
new class that we call an ns-managed
object imagine ns-managed object
actually is a generic data object so you
can use it with an arbitrary entity in
your model and that's what we did with
the demo so far there are no custom data
object classes in there so we just use
the ns-managed object and you know it's
not doing main very smart things it's
just storing getting in and setting
values and it's performing the
validation rules but for your own custom
logic you will subclass that and then at
your own specific code for a problem
domain inside those subclasses that said
ns-managed objects are probably
sufficient for many cases if you don't
need anything special just stick with
ns-managed object it's much more
convenient when you subclass you
typically implement your own logic in
the normal setters and getters that are
defined with key value coding the naming
schemes we defined with Coverity coding
observing the same is true for
validation and we all
to edit a bunch of hooks notifications
for you in your objects that you have
methods that you can override to react
to different kind of state changes and
I'd actually like to work you know
through most of the API of ns-managed
object the init method takes two
arguments first of all the entity that
the object actually represents the
second argument is this ns-managed
object context james are referred a
little bit in the in his demo and the
managed object context is the object
that does all the work for you the
triggers the undo and redo with triggers
the validation every managed object
always needs to be assigned to a managed
object context the first thing you
should do if you create a new object is
inserted into a managed object context
there's a get method for it and there's
also a method to get the entity of the
object and getting the entity can be
very handy at runtime if you want to do
some introspection it's actually very
similar to using the classification
stored in the objective-c runtime you
can use the entity to get more
information of your objects what
properties are there what attributes
what relationships are there to what
other entities can you navigate from a
given object those kind of things
manager object can't manage objects also
have an object ID the object ID is
pretty much a unique reference that is
created when your object is stored in
the file system and it's guaranteed to
stay the same throughout the lifetime of
that object so if you have any need to
get a hold of an object and then stored
away and get back to it later that
object ID is a good reference for you to
use to react to state changes they're a
bunch of methods you can override first
of all there are some get method method
just is inserted is updated it's deleted
they just tell you about the state of
the object and they are very handy in
the context of bindings for example you
can wire up the enabled binding of a
textview to one of these methods if you
only want it to be added to within
certain situations their methods that
inform you if the object was just
fetched inserted
typically you initialize your own caches
in those methods and their methods I
tell you that the option is about to be
deleted or saved and here you can
typically set some values maybe
timestamp right before it's saved
something like that
for QA recording and observing we just
followed the normal standards the
generic methods are value for key and
set value for key you typically don't
override those methods directly but
instead you implement your own accesses
those generic methods call out into
custom versions of these of the Coverity
coding methods like set name and name to
get the name property one thing that's
new in this release is that you also
added support for set mutaters if you
want to modify too many relationships
since they are we represented by sets in
this release they work the same way as
the array mutaters worked in the last
release you pretty much get a hold of a
mutable set for a given key and then you
modify that set and that modifies the
relationship indirectly there two more
things that are interesting in the
context of Coverity coding and observing
with managed objects number one is that
you will typically still want to access
the generic data storage mechanism of
managed objects you don't need to at
your own aivars to store your values you
can continue to use the generic
mechanism and actually you command that
you do there because we can optimize the
access to the values much better if you
continue using that generic storage
mechanism so to access the values we
added the primitive Coverity coding
methods primitive value for key and set
primitive value through key and again
you use them in your own custom accesses
like set name and name to call out into
the generic storage mechanism and then
the access need to be wrapped by real
change and did change methods and also
now they access and did access methods
and the read methods key value observing
actually has this really nice behavior
to do this automatically for you you
don't have to implement it for nsobject
yet we hope to have that ready by the
end of the release membership but at
this time you would have to explicitly
call really change and did change in
your set methods and video access and
did access and your get methods so this
would be an example if for example you
have a social security number of
property and the set method would jump
out in the very first call will change
then access to set primitive value for
key and then called the did change
method the get method would first call
they access then primitive value for key
and then did access and of course you
can insert your own code in between here
if you want to do your own
customizations
for validation it's very similar the
generic method is validate value for key
error again you typically don't
overwrite that directly instead you
implement those custom methods because
unlike validate name error and there are
additional methods for the state changes
so you can validate the state changes so
validate for the lead insert an update
you can deny delete for example those
would be two concrete examples again
it's a social security number to first
check whether the values actually of a
value type and then maybe check the
length and if it's not the right one you
can create an error and also you can
deny an insert you can pretty much
intercept a safe and deny that safe if
the social security number isn't set yet
so let's look at the architecture of
core data and what actually happens to
your managed objects what very heard is
that the managed objects are obviously
signed to manage object context that's
the object that as most of the work for
you and to the UI side the managed
object context are simply hooked up
usually to cocoa bindings to the UI you
don't have to use bindings we saw an
example for the carbon UI for example
but it's the most convenient way
actually to handle managed objects so
you simply hook up the controller a
cocoa bean is controller to the managed
object context it will then go and you
know filter the objects out that I need
to be displayed in the UI it will sort
them prepare them for the UI and then
populate the user interface to the other
side of the persistence side manager
object context is hooked up to
persistentstorecoordinator that
coordinator is the one that provides the
model so it tells the managed object
context of what types of entities are
available and it's also the the object
that synchronizes the access to the
different data files of your application
let's take a step back in summarize
quickly the match object context is the
center of your new word it's really the
thing that manages everything for you it
does and when we do it triggers
validation maintains the inverse
relationships that I mentioned before
all that work happens in the managed
object context it says the Gateway to
the persistentstorecoordinator
and if you want an analogy for it it's
something like a scratch pad it allows
you to load objects into memory from the
fires then modify them and them either
save them back to the fight system or
just throw the changes that way if you
don't need them anymore this is the
store Cornett coordinators the instance
that provides the model it synchronizes
the access to the persistent stores and
the idea really is that if you use my
tab it stores multiple files at the same
time it represents some like a unit of
them so it merges the context the
content of all the files together into
the managed object context it just looks
like it's talking to one single data
source what's important here for this
first release is that the only supports
striping in this versity so you can
merge the content of different data
files together in one context if you
don't support mirroring I want to talk a
little more about memory management I'd
already mentioned that vivid will give
you good scalability by only keeping the
pieces of your object graph in memory
that I actually needed needed means that
the objects are either changed or they
are currently displayed by the UI or
referenced by any other part of your
application and then core data will make
sure that your object graph grows on
demand if you did and go deeper into
your object graph and one concept I want
to mention here is the concept of
forwarding most of the time let's go
back to actually the example that we had
before the XML file that we showed in at
the beginning you have an event
management system and it's common that
you look at you know a table of data
objects but you know if you drill down
it's uncommon that you actually take a
look at all the objects in your data
file so we will make sure that we only
fetch those up into memory that that are
needed but use developer you shouldn't
have to vary about whether an object has
actually been fetched into memory
whether it has been fully initialized or
not and so the concept that you see as a
console of the place holder objects
essentially when you fetch not read into
memory is surrounded by little
placeholders that we call faults and
those faults are not fully initialized
so we haven't done the work to actually
go to the persistent store and get the
data from it so it saves a lot of time
and memory there but the placeholder
object is a valid reference so let's say
you have
that event object that has tasks
assigned to it the task objects can't be
referenced those place orders are vetted
references you don't have to worry about
whether those are fully initialized or
not and we do that pretty much
automatically for you the good thing for
you is that you don't have to worry
about whether the update has been
fetched into memory or not for you is
completely transparent in a typical
document based application you will use
multiple stacks of core data imperative
it stacks that are completely isolated
so each document will typically have its
own managed object context its own
persistentstorecoordinator and we
typically talk to a single document in a
non document based application you
usually have multiple stores that you
want to combine you might have a store
in the users home directory some
additional ones in the network and maybe
you even have removable media that
contain additional data files additional
stores so then again the
persistentstorecoordinator manages the
access to all these files at the same
time and it presents a unit of the the
stores to the to the managed object
context let's take a look at what
happens if you actually fetch Optus if
you load objects into memory typically
request is triggered by the UI layer for
example a nib file is loaded that
contains the controller that control is
hooked up to a managed object context
and then it's trying to populate the UI
if it submits um that we call it a fetch
request to the managed object context so
it's going down the stack the managed
object context we forward that request
to the persistentstorecoordinator which
we take a look at the model and then
decide what kind of data file it needs
to access it will load the objects from
the data files and send the data to the
managed object context which would then
materialize that object graph and then
the controller will filter out which
ones actually need to be displayed in
the UI which sort and prepare them and
then populate the user interface and
then over time when you fetch more
objects if you have maybe load
additional lip files so if you look at
different master detail relationships
the object graph would simply grow over
time
and changes happen those changes usually
start in the UI the user goes into text
field and enters a new value
but the help of the controller to then
access data objects and will start
applying new values to the data objects
and that in turn will cause a key value
observing notification to be sent out so
the match object context will be
notified of the changes in the object
graph and ever then you know start the
the tracking the changes it will start
undoing redo managing the undo manager
all these things essentially managed
object context will observe all the
changes to your object graph over time
so if additional objects change the
simply track all that if objects are
inserted if objects are deleted if you
keep track of all these changes and then
when you save that request usually again
starts in the UI it ends up on the
managed object context and the metric
context within package up all the
changes or the data to your object graph
sent them to the
persistentstorecoordinator which we can
take a look at the model to find out
which data files the changes have to go
to update the data files for you and
then onsuccess to notify the managed
object context which we set the object
graph to a clean state and then
everything starts from the beginning I'd
like to introduce you to one more
concept that is very fundamental to core
data and that's the cancer of predicates
predicates defined theaters they used
for queries and typically you either
predefined them in the model a
u-substitution variables for which you
can then substitute the concrete values
at runtime or you create them
programmatically which is usually based
on the user input for example in a
search field you can evaluate predicates
both in memory if you already have
objects fetched you can filter them out
in memory and sometimes we decide to
translate a predicate into another query
language in the context of sqa
we want to make use of the capabilities
of the SQL database which can do the
various very optimized and very fast so
you would translate those predicates
into SQL and perform the fetch there and
as predicates the classes represent
predicates also used outside of the core
data context the new metadata API in
cocoa uses predicates we also use it to
implement
in DNS or a controller these are some
examples for predicates you can ride
starts with simple comparisons
comparisons like name equal tom the
support case entire critic insensitive
lookups contains is the operator and
then you can have an additional flag the
see for case insensitive and the D for
diacritic insensitive you support
logical operations and or not we allow
you to look into relationships four to
one relationship you simply just follow
a key path like group dot name four to
many relationships we give you digital
operators like all in any so you can
look up persons for which all children
are older than twelve or just some of
them and we even support things like
simple operations like for computing the
sum of all the prices of some items in
the list so as you can see there's a lot
of flexibility here in predicates to
define your types of the types of
queries you want to perform on your data
objects at runtime predicates are
represented as a tree of NS predicate
objects that three classes you will
encounter and its predicate is the
abstract superclass and this compound
predicate is the class of represents
logical gates like and or not and then
this comparison predicate is the
predicate that performs all the
different operators the different
comparisons like less than greater than
contains matches there's a list of
operators we support comparison
predicates use and its expression
objects to provide the extra computation
values and their different types of
expressions again their expressions for
constant values expressions that follow
key paths again there's a list of
different types of expressions we
support but I think it's really
important for you is that the predicate
architectures extensive is you're not
limited to the datatypes v support if
you want to define special operators
that work on NS colors on NS images
you're free to do so with the predicate
architecture and now i think we have
another demo for you a bill is going to
just show you some predicates in action
okay
so I'm first going to show you just
briefly a little application that I use
to pull a bunch of data and mostly I
just wanted to show the model briefly
because this will be the model that will
be used for the other demos this is
actually an application that will go out
to Amazon through their public API will
pull a bunch of information about books
you search for and then we'll populate a
core data database so if I wanted to I
could go out and say you know search for
everything with cocoa in it and it's
going out making a WSDL based web
services soap call to Amazon pulling the
data back throwing in a core data
datastore and then throwing it up in our
default user interface including cover
art so that's just a simple little app a
few lines of code so that's our data
model there what we're going to be
looking at is products and manufacturers
Amazon uses manufacturers because they
make more than or they sell more than
books so think of them as publishers so
let me close that down and go to book
lists so I decided I wanted a little
application that I could use to grab a
bunch of books from Amazon and start
building up my wish list so I wrote a
little app and let me go ahead and open
some data book data as you can see I get
a big list of books and their prices and
and etc and now I can apply some
predicates to it so the first predicate
I'm going to apply is just a very simple
one I want to find all the books or all
of the entities of type product that
have the product name contains the word
cocoa so you can see it's executed in
there it is
now predicate scan also do some more
complex things like I can say show me
all of the books at Amazon or the price
is between 15 and 25 dollars as well
since predicates are all based on key
value coding and it should be emphasized
that they aren't limited to just managed
objects they will work with any object
in the system that's key value code and
compliant I can also follow key value
paths so in this case I'm going to ask
all of my products for all of their
manufacturers and then ask if
for all manufacturer names that begin
with O'Reilly so as you can see there
it's actually following the key path and
looking for O'Reilly and I get my list
of books from O'Reilly now I can also do
things where I'm testing if one object
is in a set of objects that are related
to another set of objects so in this
case if I want to go in and find
everything on Microsoft press and
mcgraw-hill and addison-wesley and Sam's
I can do that now I should actually show
you a little bit of code here so this is
a simple little application to apply the
predicate in the first place that's not
it there it is this is the line of code
I should scroll a little bit these are
the two lines of code necessary to
create a predicate and apply it to an
array the first line will actually take
that string that you saw in the user
interface those were actual real live
predicate expressions it will evaluate
it turn it into a predicate object which
you can then programmatically query or
take apart if you want to and then it
will apply it to an array and return the
array of objects a result from it
there's also a mutable array version of
this you can take a mutable array full
of objects and reduce it by whatever
objects passed the predicate the second
example also shows how to do custom
predicates so in the case of this user
interface I needed to basically check to
see if a particular product has a
manufacturer of this set of
manufacturers I have selected in this UI
and in that case in this line of code
I'm actually creating a comparison
predicate and comparison predicate Sall
ways have a left expression and a right
expression so in this case I'm saying
the left expression is the evaluated
object and all that means is that it's
it's the object in the array of books
that I'm trying to filter it's the thing
I want to filter and the right
expression in this case is a constant
value and it's my selected manufacturers
it's just whatever I have selected in
here
and in this case I said I want to use a
custom selector which is number of array
and this is going to be a method that's
going to be invoked on objects from the
left hand side and it will take an
argument from the at the right hand side
will be the argument passed to it so in
a category an ns-managed object because
in this demo we're using nothing but
managed objects
I wrote the member of array method which
as you can see it's pretty
straightforward
so using this leveraging this you could
like Andre said you could qualify
anything you could predicate you know
any object as long as you have key value
coding and as long as you can express
your expression in a method that takes a
single argument returns a boolean now if
you get into expressions which are more
complex then you can open it up even
further now I have one more demo we at
Apple like to eat her own dog food so
this is actually the core data
predicates are being used by metadata in
the Objective C API - metadata so let me
go ahead and run this application and it
comes up and it gives you a field and
you can type query into it which is
going to be a metadata query and it will
show a list of files of result so for
example I can ask it show me all files
let's start with the word app delegate
in their file name and it takes a second
but there comes and you can see that the
results are filling in as it goes this
is again because it's all leveraging key
value observing and key value binding we
can do some more complex queries like
for example I have a metadata importer
that grabs Objective C metadata from
Objective C source files so in this case
I'm going to find all files on my hard
drive that implements subclasses of NS
view which is pretty handy if you want
to find stuff in the example code now
let's look at the code so the code for
this is actually quite straightforward
and you can ignore the Notification
Center stuff that's a unfortunate hack
necessary to make the demo work right
now it goes
whay doesn't exist those lines not there
so we simply create a query and then
we'd set the predicate on the query and
again you see that line of code
predicate will format argument array and
that's it
start the query you're done so those are
predicates okay what does it mean for
you to start using core data if you want
to use core data you your application
will actively have to opt in you would
have to let core data drive you also
have to make a few changes to your
source code as I mentioned we expected
to use ns-managed objects for your data
objects and those need to follow very
strictly the Coverity coding and key
value observing conventions one thing
that might help you is that you can opt
to only use the in memory logic and not
the persistence logic of the framework
so you can still leverage undo and redo
and validation but continue to use your
own file formats and and save and and
open save and load your objects by hand
and then you know switch to Core Data
later again if you switch to core data
the full stack with the persistence
piece then you will lose detailed
control over the file formats and this
current release so I think adopting core
data is going to be little harder than
cocoa bindings but I also think that the
benefits will be much larger for your
applications of course the seed you have
in your own hands right now is these are
very early bits so not everything is
fully working right now
SQLite your is sort working here on
stage but the access for you and the
seed is not available right now the
other two things worth mentioning is
that controllers and as life as we'd
like them to be right now we like them
to react much better to adding and
removing persistent stores on the fly
and then update the UI automatically if
you don't have all that implemented yet
and also fetch properties aren't
supported at this time and of course the
little things like localization better
error messages leaks optimizations that
are still forthcoming that said
the complete API can be completely
exercised with the xm8 store that
actually works fully in the seed that we
have so we would like you do
this big overt watch sorry
so please try it out and we would like
to get your feedback you can send email
to Coco feedback at Group a tepid calm
or you can submit back reports actually
submitting back report is probably the
best way for you to communicate via
requests and ideas and also the Box you
encounter the documentation there's some
good use there's already a good amount
of documentation available that's listed
here on the slide if you don't have
really do release notes but we have very
good base documentation already and
that's on the seed that you in the seat
that you have
so in summary core data is a model
driven framework it manages your objects
it persists your objects it
automatically updates your UI through
cocoa bindings it's solve some very
difficult problems like undoing video
and gives you great scalability it gives
you choice and persistence stores we
support SQL databases XML files and
binary files we have added some good
support in Xcode for modeling there's a
great modeling tool for you and really
the benefit for you is that you will
read a lot or significantly less code
you would be a lot faster while you
develop your application so that was my
summary the good news for you is there
there's going to be a second summary
the Germans
[Applause]
so last year we had a little song to go
with cocoa bindings called
model-view-controller
and this year with the focus on core
data and building some data models since
the song writing tends to go where the
technology leads me it's a little song
about data modelling so we need to
switch over to the laptop excellent so
hope you like it
Modelling man I'm a modeling man they
say are you in modeling I say oh yes I
am
there's no catwalk involved in the
modeling I do there's no demand for me
to try that kind of model into some
people wanna date a model for a new
application don't wanna write a lot of
code simply use configuration to refine
your data model with each new iteration
as you build a prototype with
persistence automation some people want
to date a model but prefer one in
fashion if you date a data model that's
an interest in passion you're a dreamer
with a schema you can usually cash you
know you ain't got the looks in your
clothes they are clashing modeling man
I'm a modeling man let me lay it all out
so that you will understand you'll have
the terminology and concepts at your
command so you can also be a modeling
woman or man
we're Hill a managed object model also
known as the mom describes the data
objects that your app backs upon you
design your data model as pretty as you
please
by adding items to the model known as
entities and entities are a Pawnee is
one of things supposed to be what type
would sort what class will kind whatever
you might have in mind you pick a name
map to a class now your models growing
fast you work some more and come to
grips with attributes and relationships
now baby now your model into I said Ave
there one more for a model Amanda - and
attribute our relationship is known as a
property no not the kind that they using
monopoly using terms with precision
don't use them sloppily all confusion
will ensue like episodes a Three's
Company
I said I'm modeling man I'm a modeling
man EW and modeling I say oh yes I am
there's no photographers involved in the
modeling I do I got turned down by
everyone I gave my headshot to
[Music]
[Applause]
[Music]
and attributes a sample value string
number all dates or a big old blob of
data that's contained in some states you
can mark it transient if you don't care
about its fate otherwise it will persist
and data stores are you created two
entities can be connected kind of joined
at the hip the formal name for this
arrangement is a relationship one object
references the other so it can't give it
the slip the inverse reference is
maintained for a convenient roundtrip I
said I said a modeling man yeah I'm a
model and man they sell you and model
and I say oh yes I am
but don't come knockin if it's rockin in
the back of the van I'm probably
wrestling with relationships I don't
quite understand
Modelling man I'm a modeling man they
say are you and model and I say oh yes I
am
it's not too glamorous you know that
kind of modeling I do I'd like to see a
supermodel build the apps that we do
[Music]
[Applause]
Wow
so I've the boring task to finish up the
session if you could expect the slides
there are a few more sessions I'd like
to point you to that are related to core
data using a customizing cocoa bindings
this afternoon 5 we'll have a new piece
on the UI part of core data tomorrow
morning at 10:30 there's advanced core
data and on Friday morning at 9:00 we
have an overview of the modeling tool in
depth modeling design in Xcode these are
the usual people to contact