|
From: kimura w. <ki...@us...> - 2005-11-04 11:21:42
|
Hi,
I'm trying this tutorial.
Thu, 3 Nov 2005 23:13:03 +0000, Jonathan Paisley wrote:
>On 3 Nov 2005, at 21:31, Rupert Barrow wrote:
>
>Since you're using Core Data, all the data members of the class are
>already managed for you. Therefore, you should not define firstName
>and lastName as accessors, nor should you use ruby @firstName/
>@lastName variables.
>
>Instead, just access firstName etc as if it were already defined as
>an accessor (or perhaps you need to use setValue:forKey: and
>valueForKey:). RubyCocoa will forward the call through to Objective
>C, where Core Data will handle the request for you.
>
It's right. To access attributes of an Employee, we have to use
setValue:forKey and valueForKey:.
for example:
------------
def fullNameAndID
return OSX::NSString.stringWithString(valueForKey("lastName").to_s +
", " + valueForKey("firstName").to_s)
end
------------
I felt that was not smart. I defined a method "kvc_wrapper". This method
defines accessors wrapping "valueForKey:" and "setValue:forKey:".
# tell me a better name of "kvc_wrapper", please.
my Employee.rb:
---------------
require 'osx/cocoa'
require 'osx/coredata'
# add kvc_wrapper
module OSX
module NSKVCBehaviorAttachment
# accessor for keys defined in Cocoa
def kvc_wrapper(*keys)
keys.each do |key|
class_eval <<-EOE_KVC_WRAPPER,__FILE__,__LINE__+1
def #{key}
valueForKey("#{key}")
end
def #{key}=(val)
setValue_forKey(val, "#{key}")
end
EOE_KVC_WRAPPER
end
end
end
end
# Employee class
class Employee < OSX::NSManagedObject
kvc_depends_on [:lastName, :firstName], :fullNameAndID
# define wrappers
kvc_wrapper :lastName, :firstName, :employeeID
def fullNameAndID
sprintf('%s, %s (%d)', lastName.to_s, firstName.to_s, employeeID)
end
end
---------------
I think that is possible to define wrappers automatically from
NSManagedObjectModel#entities -> NSEntityDescription, but I do not
know how to implement.
--
kimura wataru
|