When mirrored: Should set property or directly set value? (Objective-C)

I am writing an xml serialization class for objective-c.
The point is to give the class a class type and an XML file. It should return an instance with data.

This works for me, and it doesn’t work much - it processes primitives (+ nsstring), user classes and nsarrays. Does not handle pointers or C arrays.
Obviously, this is highly dependent on reflection.

Question: When I set the value of an instance of a certain class, should I check if the property with the correct name exists, or can I just set the variable with a simple reflection?

This is the code I've used so far:

id newClass = class_createInstance(NSClassFromString(elementName), sizeof(unsigned)); Ivar nameVar = class_getInstanceVariable([newClass class], "name"); if (nameVar != nil) object_setIvar(newClass, nameVar, [NSString stringWithString:@"George"]); 

Also, after this kind of assignment, should I let go of something?

+4
source share
1 answer

Uh ... you usually don’t need to run so low at runtime to do what this code does. The following is fully functional and does the same:

 id newObject = [[NSClassFromString(elementName) alloc] init]; @try { [newObject setValue:@"George" forKey:@"name"]; @catch (NSException *e) { if ([[e name] isEqualToString:NSUndefinedKeyException]) { NSLog(@"%@ does not recognize the property \"name\"", elementName); } } //... do stuff with newObject [newObject release]; 

If you need to add other things, such as float or ints or structs, you can put them in NSValue (or a subclass) and then pass them to setValue:forKey: For instance:

 NSNumber * aFloat = [NSNumber numberWithFloat:42.0]; [newObject setValue:aFloat forKey:@"aFloatIvar"]; NSRect frame = NSMakeRect(0, 0, 42, 54); NSValue * aStruct = [NSValue valueWithBytes:&frame objcType:@encode(NSRect)]; [newObject setValue:aStruct forKey:@"aStructIvar"]; 
+6
source

All Articles