开发者

How to create an instance of any type (id) in Objective-c

开发者 https://www.devze.com 2023-04-07 10:47 出处:网络
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.

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 al开发者_运维技巧loc] 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:

Type of objects inside non-parameterized arrays in JSON


Change:

id newObj = [[NSObject alloc] init];

to:

id newObj = [[NSMutableArray alloc] init];

or:

id newObj = [[NSClassFromString(@"NSMutableArray") alloc] init];

or, if you want to derive the class from an existing object:

id newObj = [[[existingObj class] alloc] init];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号