我正在尝试学习如何利用 Objective-C 运行时函数。
我有一本字典,其中包含几个name=value
pairs.
E.g.
{
"recipe_description" = "Delicious and healthy.";
"recipe_id" = 7042366;
"recipe_image" = "http://www.fatsecret.com/static/recipe/b5b8ccb7-badd-4a7f-8dd4-0ffe4aba8c6d.jpg";
"recipe_name" = "Brown Rice & Cherry Tomato Cooked Salad";
"recipe_url" = "http://www.fatsecret.com/recipes/brown-rice-and-cherry-tomato-cooked-salad/Default.aspx";
}
首先,我创建一个运行时类,其中包含与字典中每个对象的键关联的 ivars(例如 ivars = Recipe_description、recipe_id、recipe_image 等)。其次,我将运行时类中每个 Ivar 的值设置为字典中每个相应的对象(例如,recipe_description = Delicious andhealthy 等)。最后,我检索了 Ivar 的值。
我可以检索recipe_name、recipe_id 和recipe_description 的值,但无法检索recipe_url 和recipe_image 的值。当我尝试检索这些值时,我得到一个EXC_BAD_ACCESS code=2, address=0x5
线路错误value = object_getIvar(classInstance, ivar);
in the valueForIvarContainingName:class:
method.
Code:
- (Class)wrapObjectWithName:(NSString *)name ivarNames:(NSArray *)ivarNames
{
const char *className = [name cStringUsingEncoding:NSASCIIStringEncoding];
Class objectClass = objc_allocateClassPair([NSObject class], className, 0);
for (NSString *key in ivarNames)
{
const char *iVarName = [key cStringUsingEncoding:NSASCIIStringEncoding];
class_addIvar(objectClass, iVarName, sizeof(NSString*), log2(sizeof(NSString*)), @encode(NSString*));
}
objc_registerClassPair(objectClass);
return objectClass;
}
- (void)mapValues:(NSDictionary *)dictionary toVariablesInClass:(id)classInstance
{
NSArray *dictionaryObjectKeys = [dictionary allKeys];
for (NSString *key in dictionaryObjectKeys)
{
const char *iVarName = [key cStringUsingEncoding:NSASCIIStringEncoding];
Ivar ivar = class_getInstanceVariable([classInstance class], iVarName);
id value = dictionary[key];
object_setIvar(classInstance, ivar, value);
}
}
- (id)valueForIvarContainingName:(NSString *)anIvarName class:(id)classInstance
{
unsigned int outCount;
Ivar *iVarList = class_copyIvarList([classInstance class], &outCount);
id value;
for (int i = 0; i < outCount; i++)
{
Ivar ivar = iVarList[i];
NSString *ivarName = [NSString stringWithCString:ivar_getName(ivar) encoding:NSASCIIStringEncoding];
if ([ivarName rangeOfString:anIvarName].location != NSNotFound)
{
value = object_getIvar(classInstance, ivar);
break;
}
}
free(iVarList);
return value;
}
Usage:
NSArray *ivarNames = [dictionary allKeys];
Class FSRecipe = [self wrapObjectWithName:@"FSRecipe" ivarNames:ivarNames];
id recipe = [[FSRecipe alloc] init];
[self mapValues:dictionary toVariablesInClass:recipe];
NSLog(@"%@", [self valueForIvarContainingName:@"image" class:recipe]);
为什么我可以检索recipe_name、recipe_description、recipe_id 值,但不能检索recipe_url 和recipe_image 值?
我猜这可能与 URL 对象有关?我尝试将字典中的每个对象转换为字符串,但这没有效果。
任何帮助是极大的赞赏!