I need to use reflection/introspection in objective c. I am able to create instance by writing;
id object = [[NSClassFromString(@"UIView") alloc]init];
At this point, i also want it to set its frame.
I have written the code piece below, but it does not compile.
SEL method2 = NSSelectorFromString(@"setFrame:");
CGRect rect = CGRectMake(0, 0, 1024,768);
NSValue * value = [NSValue valueWithCGRect:rect];
[object performSelector:method2 withObject:value];
How can i pass the parameter to setFrame or setBackgroundColor method of an object.
Could you please help me to figure it out?
Thanks in advance
edit
i have found the solution i want,
there is a method called CGRectFromString(NSString*)
it solved my problem.
i am able to set the frame of a view with the code below
SEL method2 = NSSelectorFromString(@"setFrame:");
if([object respondsToSelector:method2])
{
[object setFrame:CGRectFromString(@"{{0, 0}, {1024, 768}}")];
}
Try something like this, in my opinion it is more clear and straightforward. Note the the respondsToSelector
is just to avoid crashing by sending a method to an object that does not implement it (in your question you are not checking that, so maybe is not needed in your case).
id object = [[NSClassFromString(@"UIView") alloc]init];
if(object respondsToSelector:@selector(setFrame:)){
[object setFrame:CGRectMake(0, 0, 1024, 768)];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.