Objective C 类到 NSDictionary
我将 NSDictionary 发布到 JSON Web 服务,以将数据保存回本地数据库。将 Objective C 类转换为 NSDictionaries 的最佳方法是什么?
这是我当前的代码,除了编写更通用的版本之外,这是最好的方法/唯一的方法吗?包括
对于苹果来说可以吗?
- (NSDictionary*)dictionaryFromContact {
Class contactClass = [self class];
u_int count;
objc_property_t *properties = class_copyPropertyList(contactClass, &count);
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:count];
for (int i = 0; i<count; i++) {
NSString *str = [NSString stringWithCString:property_getName(properties[i])
encoding:NSUTF8StringEncoding];
//Set the dicationary values from our properties
[dict setValue:[self valueForKey:str] forKey:str];
}
free(properties);
return [dict autorelease];
}
谢谢!
Iam posting a NSDictionary to a JSON webservice for saving my data back to a local database. Whats the best way of converting Objective C classes to NSDictionaries?
Here is my current code, except from writing a more generic version, is this the best way/only to do this? And including <obj/runtime.h>
is OK with apple?
- (NSDictionary*)dictionaryFromContact {
Class contactClass = [self class];
u_int count;
objc_property_t *properties = class_copyPropertyList(contactClass, &count);
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:count];
for (int i = 0; i<count; i++) {
NSString *str = [NSString stringWithCString:property_getName(properties[i])
encoding:NSUTF8StringEncoding];
//Set the dicationary values from our properties
[dict setValue:[self valueForKey:str] forKey:str];
}
free(properties);
return [dict autorelease];
}
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
class_copyPropertyList
是合法的。您可以考虑使用dictionaryWithValuesForKeys:
作为快捷方式。如果您将
Core Data
用于本地数据库,则应使用attributesByName
和relationshipsByName
或propertiesByName
。class_copyPropertyList
is legit. You may considerdictionaryWithValuesForKeys:
for shortcut.If you use
Core Data
for local database, you should useattributesByName
andrelationshipsByName
, orpropertiesByName
.查看 对象映射 功能/restkit.org" rel="nofollow">RestKit,它可能会满足您的需要。
Have a look at the Object Mapping feature of RestKit, it might do what you need.