如何在 Objective-c 中创建任意类型(id)的实例
我有一个 NSArray 实例,其中包含某种类型(NSDictionary)的一些对象。
我需要将此数组复制到某种运行时已知类型的 NSArray 中。
因此,我需要创建运行时已知类型的实例并将 NSDictionary 的内容复制到其中。
我实际上已经创建了这些 NSObject 类型的实例,但是在头后查询它时,我收到了无法识别的选择器
错误!
NSUInteger count = [value count];
NSMutableArray* arr = [[NSMutableArray alloc]initWithCapacity:count];
if (count > 0)
{
for (int i=0; i < [value count]; i++)
{
id newObj = [[NSObject alloc] init];
id currentValue = [value objectAtIndex:i];
[self objectFromDictionary:currentValue object:newObj];
[arr addObject:newObj];
}
}
[arr release];
编辑: objectFromDictionary
忘了它吧,它所做的就是检查 newObj
的属性并通过字典中的值设置它。它的工作做得很好。
编辑2:
请看看我为什么要这样做:
I've an NSArray instance containing some objects of some type (NSDictionary)..
I need to copy this Array into an NSArray of some runtime-known type.
So I need to create instances of the runtime-known type and copy the contents of the NSDictionary into.
I've actually created these instances of type NSObject, but when querying it after-head, I got unrecognized selector
error!
NSUInteger count = [value count];
NSMutableArray* arr = [[NSMutableArray alloc]initWithCapacity:count];
if (count > 0)
{
for (int i=0; i < [value count]; i++)
{
id newObj = [[NSObject alloc] init];
id currentValue = [value objectAtIndex:i];
[self objectFromDictionary:currentValue object:newObj];
[arr addObject:newObj];
}
}
[arr release];
EDIT:objectFromDictionary
forget about it, what it do is to inspect the properties of newObj
and set it by the values from the dictionary. it is doing its work good.
EDIT 2:
Please see why I am trying to do this:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将:更改
为:
或:
或者,如果您想从现有对象派生类:
Change:
to:
or:
or, if you want to derive the class from an existing object: