Problem when accessing an object (UIView) with another class object!
I have two classes A and B.
Class A contains a UIView named myView and also a method MyMethod to set the position of the myView.
-(void)MyMethod:(NSString *)justCheck
{
[self.view addSubview:myView];
[self.view bringSubviewToFront:myView];
CGRect mframe = [myView frame];
NSLog(@"------------> MyMethod Called = %@",justCheck);
// EDIT: the following NSLogs are added later--------------------
NSLog(@"------------> MyMethod Called:mframe:x = %g",mframe.origin.x); //0
NSLog(@"------------> MyMethod Called:mframe:y = %g",mframe.origin.y); //42
NSLog(@"------------> MyMethod Called:mframe:H = %g",mframe.size.height); //317
NSLog(@"---开发者_Python百科---------> MyMethod Called:mframe:W = %g",mframe.size.width); //320
//---------------------------------------------------------------
mframe.origin.y = 42;
[myView setFrame:mframe];
}
When a button in the class A named buttonOfA calls this MyMethod, it works perfectly and I can see the myView in position 42. code is as below,
-(IBAction)buttonOfA:(id)sender
{
[self MyMethod:@"I am A"];
}
But, when the button of class B named buttonOfB tries to call this method, NSLog works but I cannot see the myView in position 42. Code as below,
-(IBAction)buttonOfB:(id)sender
{
[objOfA MyMethod:@"I am B"]; //objOfA is the object of class A
}
What is happening here?? I have been trying hard to figure out the problem, But I couldn't. Plz help me.
Thanx :)
EDIT: four NSLogs are added in myMethod()
Make sure the myView
instance variable in the class A object is initialized and added to a super view when class B calls MyMethod:
on it. Otherwise setting the frame won't have any effect.
Hold a reference to the object of type A, but it should be the same object which created the UIView. Hence it is better to return the singleton instance of the object.
Using the returned singleton for the Class A object call your method.
because myView is not a property just make it property of class A and do this work
-(void)MyMethod:(NSString *)justCheck
{
CGRect mframe = [self.myView frame];
NSLog(@"------------> MyMethod Called = %@",justCheck);
mframe.origin.y = 42;
[self.myView setFrame:mframe];
}
To make it a property instead of declaring it as UIView* myView;
Do it as like this in .h
file
@property(nonatomic,retain) UIView* myView;
and in .m
of class A
do it like this
@synthesize myView;
and you don't have to change anything in code just replace all myView
with self.myView
精彩评论