I want to create a "business object" based on a NSDictionary. The reason for this is that I want implementations to be able to extend this object with arbitrary keys, and another reason is that I am persisting it using the convenient plist format (the objects stored are either integers, floats or strings).
The business object contains a number of predefined properties, e.g.
#property NSString* customerName;
#property NSString* productCode;
#property int count;
#property double unitPrice;
I want to serialize this, for example to a property list (this is not a strict requirement, it could be some other easy-to-use format). Preferably, the implementation of the class should be just
#synthesize customerName, productCode, count, unitPrice:
for the example above. To use this class, I want to do something like:
MyBusinessObject* obj = [MyBusinessObject businessObjectWithContentsOfFile:fileName];
obj.productCode = #"Example";
[obj setObject:#"Some data" forKey:#"AnExtendedProperty"];
[obj writeToFile:fileName atomically:YES];
You should make your class KVC complaint. KVC does the magic. Look here.Ex,
// assume inputValues contains values we want to
// set on the person
NSDictionary * inputValues;
YOURCLASS * person = [[YOURCLASS alloc] init];
[person setValuesForKeysWithDictionary: inputValues];
The "path of least resistance" turned out to be using NSCoding instead.
Related
I have a JSON response that I turn into a Dictionary like so:
NSError *error;
self.restKitResponseDict = [NSDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:response.body options:0 error:&error]];
I have a core data class that has the following attributes/properties:
name
image_url
When I log the restKitResponseDict from above I see that image_url is listed as "image_url" like this:
name = Rock;
"image_url" = "http://f.cl.ly/items/122s3f1M1E1p432B211Q/catstronaut.jpg";
Is this why KVC is crashing on
[CoreDataClass setValuesForKeysWithDictionary:self.restKitResponseDict];
like this:
'[<CoreDataClass 0x14132c> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key image_url.'
Do the quotes matter? Should I ask my server guy to get rid of the underscore that's likely causing it?
Core Data Class:
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#interface CoreDataClass : NSManagedObject
#property (nonatomic, retain) NSString * name;
#property (nonatomic, retain) NSString * image_url;
#end
#implementation CoreDataClass
#dynamic name;
#dynamic image_url;
#end
You are sending the method to the class object:
[CoreDataClass setValuesForKeysWithDictionary:self.restKitResponseDict];
when you probably want to send it to the actual CoreDataClass instance:
[coreDataClassObject setValuesForKeysWithDictionary:self.restKitResponseDict];
EDIT
what's the simplest way to init the object from the class? – Eric
It's a subclass of NSManagedObject, so you use the normal Core Data methods. One way to create a new object:
CoreDataClass *coreDataObject = [NSEntityDescription
insertNewObjectForEntityForName:#"YOUR_ENTITY_NAME"
inManagedObjectContext:managedObjectContext];
If you need basic information about using Core Data, see the Core Data Programming Guide: http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/coredata/cdProgrammingGuide.html#//apple_ref/doc/uid/TP30001200-SW1
The NSLog() with the %# format uses the description method to print objects, and the description of a NSDictionary puts quotation marks around all keys and values that contain any special characters, such as the underscore. For example
NSDictionary *dict = #{
#"key1" : #"value_1",
#"key_2" : #"value2"
};
NSLog(#"dict=%#", dict);
produces
2012-08-25 18:15:33.553 test27[3416:c07] dict={
key1 = "value_1";
"key_2" = value2;
}
Therefore the key in your JSON dictionary does not really have quotation marks, and the underscore is probably not the cause of the error.
The error message indicates that the managed object does not have an image_url attribute, therefore you should check that.
I am trying to introduce some generics-style approaches from .NET into my iOS development. I am retrieving a list of custom objects of type Example.
I have defined a protocol that Example class implements:
#protocol ExampleProtocol
#property(nonatomic,assign) int Id;
#property(nonatomic,copy)NSString *Description;
#optional
#property(nonatomic,copy)NSString *Icon;
#end
I then retrieve my NSMutableArray of Example as follows:
id<ExampleProtocol> anExample = [arrayOfExampleProtocols objectAtIndex:0];
The problem I have is that anExample is always empty regardless of the contents of the NSMutableArray. My ultimate aim is to be able to reference the properties with the following syntax:
id<ExampleProtocol> anExample = [arrayOfExampleProtocols objectAtIndex:0];
NSString *test = [anExample Description];
There are no generics in Obj-C. The "protocol" is a messaging mechanism. Please see this post: No Generics in Obj-C
I am working an application in which data is being populated from an sqlite database. All database related stuff is done in the appdelegate class. I have used NSMutable array to hold objects.
I have used a separate NSObject class for properties.
I am getting the error: property 'x' with 'retain' attribute must be of object type.
My appdelegate.m file's code is as:
NSString *amovieName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
NSInteger amovieId = sqlite3_column_int(compiledStatement, 1);
//problem is here the
//value of movieId is coming from database.
//But error: "must be of object type" is puzzling me.
//I am assuming to use NSNumber here.
my NSObject file's code is as:
in .h file-
NSInteger movieId;
its property as:
#property (nonatomic, retain) NSInteger movieId;
and in .m file-
#synthesize movieId;
then I have just initialize as:
-(id)initWithmovieName:(NSString *)mN movieId:(NSInteger)mId
{
self.movieName=mN;
self.movieId=mId;
return self;
}
I found another way as:
assigning value in a NSnumber object .then type caste in NSInteger.for ex;
NSNumber aNSNumbermovieID = sqlite3_column_int(compiledStatement, 1);
NSInteger amovieId = [aNSNumbermovieID integerValue];
but still I am getting the same errors(property 'x' with 'retain' attribute must be of object type).
Any suggestion?
NSInteger is a scalar and not an object. So you shouldn't retain it, it should be assigned. Changing your property will clear up the warning message. You don't need to do the NSNumber stuff that you added in.
#property (nonatomic, assign) NSInteger movieId;
It's a little confusing since NSInteger sounds like a class, but it's just a typedef for int. Apple introduced it as part of 64-bit support so that they can typedef it to the appropriately sized integer for the processor the code is being compiled for.
Just use NSNumber and you can do:
#property (nonatomic, retain) NSNumber *movieId;
I think the error is because of the #property retain for NSInteger. Assign is for primitive values like BOOL, NSInteger or double. For objects use retain or copy, depending on if you want to keep a reference to the original object or make a copy of it.
Here NSInteger is clearly not an object so you should try assign instead of retain
I'm fetching some objects out of a data store but the results aren't what I'm expecting. I'm new to CoreData but I'm fairly certain this should work. What am I missing?
Note that User is a valid managed object and that I include its header file in this code, and that UserID is a valid property of that class.
NSFetchRequest *requestLocal = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"User" inManagedObjectContext:messageManagedObjectContext];
[requestLocal setEntity:entity];
// Set the predicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"ANY UserID IN %#", userList];
[requestLocal setPredicate:predicate];
// Set the sorting
... sorting details removed but exist and are fine ...
// Request the data
NSArray *fetchResults = [messageManagedObjectContext executeFetchRequest:requestLocal error:&error];
[requestLocal release];
for (int i; i < [fetchResults count]; i++) {
[fetchResults objectAtIndex:i].UserID = ...<----HERE
}
Isn't fetchResults an array of User objects? Wouldn't [fetchResults objectAtIndex:i] be a User object? Why do I get an error when building that "request for member 'UserID' in something not a structure or union"?
Sorry if this is a basic error, I'm clearly missing some basic concept. I've done a ton of searching and it seems like it should be right. (I also tried fast enumeration but it complained that fetchResults items weren't valid Objective C objects, effectively the same error, I think.)
Update:
(from comment below)
My goal is to update the object, calling saveAction after changing it.
Does the KVC method still refer to the actual object? I tried fast enumeration with:
for (User thisUser in fetchResults) {
... but it didn't like that.
I used the more generic version:
(id thisUser in fetchResults)
...but it won't let me set
[thisUser valueForKey:#"FirstName"] = anything
... insisting that there's no Lvalue.
Will:
[[thisUser valueForKey:#"FirstName"] stringWithString:#"Bob"]
... do the trick or is there a better way? Sorry, I know it's nearly a new question, but I still don't get what is in the fetchResults array.
Your fetchedResults variable contains a NSArray object. However, a NSArray can hold any arbitrary group of objects. Unlike a standard C array, there is no requirement that the NSArray objects all be of a single class.
The dot notation you are using here:
[fetchResults objectAtIndex:i].UserID =
... while a legal syntax, nevertheless confuses the compiler because the compiler has no idea what class of object is returned by [fetchResults objectAtIndex:i]. Without knowing the class it has no idea what the heck UserID is. Hence the error "request for member 'UserID' in something not a structure or union". At the very least you have to cast the return of [fetchResults objectAtIndex:i] to some class so that the complier has a clue as to what 'UserID' is.
However, you simply shouldn't use this construction even though it legal because it is dangerous. See below for the best practice form.
Understanding NSManagedObject and its subclasses can be tricky because NSManagedObject itself uses a trick called associative storage which allows any generic NSManagedObject instances to store any property of any entity defined in any model. This can confuse novices because there are multiple ways to refer to the same entities, instances and properties. Sometimes the examples use generic NSMangedObjects and setValue:forKey:/valueForKey: and other times they use objectInstance.propertyName.
Associative storage works like a dictionary attached to every instance of the NSManagedObject class. When you insert a generic NSManagedObject like this:
NSManagedObject *mo=[NSEntityDescription insertNewObjectForEntityForName:#"User"
inManagedObjectContext:self.managedObjectContext];
... you get an instance of the NSManageObject class whose associative storage keys are set to the properties of the User entity as defined in your data model. You can then set and retrieve the values using key-value coding (which has the same syntax as dictionaries) thusly:
[mo setValue:#"userid0001" forKey:#"UserID"];
NSString *aUserID=[mo valueForKey:#"UserID"];
Associative storage allows you represent any complex data model in code without having to write any custom NSManagedObject subclasses. (In Cocoa, it allows you to use bindings which let you create entire programs without writing any data management code at all.)
However, the generic NSManagedObject class is little better than a glorified dictionary whose saving and reading is handled automatically. If you need data objects with customized behaviors you need to explicitly define a NSManagedObject subclass. If you let Xcode generate the class from the entity in the data model you end up with a source file something like:
User.h
#interface User : NSManagedObject
{
}
#property (nonatomic, retain) NSString * firstName;
#property (nonatomic, retain) NSString * userID;
#property (nonatomic, retain) NSString * lastName;
#end
User.m
#import "User.h"
#implementation User
#dynamic firstName;
#dynamic userID;
#dynamic lastName;
#end
Now, you are no longer limited by to the key-value syntax of associative storage. You can use the dot syntax because the complier has a class to refer to:
User *aUser=[NSEntityDescription insertNewObjectForEntityForName:#"User"
inManagedObjectContext:self.managedObjectContext];
aUser.userID=#"userID0001";
NSString *aUserID=aUser.userID;
With all this in mind, the proper forms of reference to the fetchedResults array become clear. Suppose you want to set all userID properties to a single default value. If you use the generic NSManagedObject class you use:
for (NSManagedObject *aMO in fetchedResults) {
[aMO setValue:#"userid0001" forKey:#"UserID"];
NSString *aUserID=[aMO valueForKey:#"UserID"];
}
If you use a dedicated subclass you would use:
for (User *aUserin fetchedResults) {
aUser.userID=#"userID0001";
NSString *aUserID=aUser.userID;
}
(Note: you can always use the generic form for all NSManagedObject subclasses as well.)
Accessing your CoreData attributes by property Accessors (dot notation) will only work if you have defined a custom NSManagedObject subclass in your Model and defined properties on that class. The implementation should be #dynamic. You'll then have to cast the object to the proper class:
//Assume this exists:
#interface User : NSManagesObject
{
}
#property (nonatomic, retain) NSString* UserID;
#end
#implementation User
#dynamic UserID
#end
// You could do:
for (int i; i < [fetchResults count]; i++) {
((User*)[fetchResults objectAtIndex:i]).UserID = ... // This works
}
Or you may use KVC to access your models properties like this (without needing a class):
for (int i; i < [fetchResults count]; i++) {
[[fetchResults objectAtIndex:i] valueForKey:#"UserID"] = ... // This too
}
You would set the value using [object setValue:newValue forKey:#"UserID"] please note, that newValue needs to be an object in general and one of NSString, NSNumber, NSDate, NSSet for CoreData.
Two additional thoughts:
Your could and should use fast Enumeration on the results array:
for (id object in fetchResults) {
[object valueForKey:#"UserID"] = ...
}
I do not understand the ANY keyword in your predicate. "UserID IN %#" should do as well.
Your basic problem is that -objectAtIndex: returtns an object of type id. No accessors are defined for type id so when you use dot notation with the object returned by -objectAtIndex: the compiler assumes you mean to access a C structure member. id is a pointer type, not a structure type, hence the error you are getting.
The whole core data stuff is a red herring with regard to this issue. You'd get the same error if User was derived from NSObject and you had populated the array yourself manually.
The ways out of it are:
Use fast enumeration
for (User* aUser in theArray)
{
....
}
which is the preferred idiom if you need to iterate through the whole array
Cast the result of -objectAtIndex: to the correct type.
((User*)[theArray objectAtIndex: i]).userId;
Use the message sending syntax instead of dot notation
[[theArray objectAtIndex: i] setUserId: ...];
Personally, I'd go with 1 and 3.
for (User* aUser in theArray)
{
[aUser setUserId: ...]
}
Clearly any of the above are dangerous if you are not certain that the objects in the array are User objects. You can use -respondsToSelector: to make sure it will work if you like.
I am attempting to instantiate classes from different XML sources. The cases of the class names are inconsistent (camel, upper, lower) across these sources. Does an equivalent to NSClassFromString exist for this? For example, something allowing for:
Person *person = [[NSClassFromCaseInsensitiveString("Person") alloc] init];
Person *person = [[NSClassFromCaseInsensitiveString("person") alloc] init];
Person *person = [[NSClassFromCaseInsensitiveString("PERSON") alloc] init];
make a NSString case insensitive by using any of the capitalization methods in NSString (-capitalizedString for instance) then use it as the param for NSClassFromString
Edit: here is code based on your Person example. (Assuming stringFromXML is a NSString that you parsed from your XML code that could contain any form of the word "person"
NSString *personString = stringFromXML;
Person *person = NSClassFromString([personString capitalizedString]);
You're probably stuck with searching the class list, obtainable from objc_getClassList
Please don't do this. You're letting arbitrary (I'm assuming downloaded-over-HTTP) XML instantiate arbitrary classes in your app. This is bad, and it's difficult to know how bad because it can instantiate any class loaded in your app (including ones in private frameworks).
Consider using something like
NSDictionary * classesByLowercaseString = [NSDictionary dictionaryWithObjectsAndKeys:
[Person class], #"person",
[Blah class[, #"blah",
nil];
[classesByLowercaseString objectForKey:[xmlClassName lowercaseString]];
Also note that XML tag names are supposed to be case-sensitive.
You could use the NSString capitalization methods, if you are guaranteed that the class name will look like that. A general function as you describe is not available, and likely won't be, for the simple reason that class names are not case insensitive.
#interface Person : NSObject
{
}
#end
#interface PERSON : NSObject
{
}
#end
will work and declare two different class types. Though in all honesty, having classes with identical names except case would just be bad style in the first place.