Objective C scope problem

2019-08-22 02:31发布

问题:

I have the following Obj C function that works properly:

 NSString* myfunc( int x )
 {
    NSString *myString = @"MYDATA";

    return myString;        
 }

However if I add code to update a UIImage the compile fails with image1 being unknown. image1 is valid: it's set up in the .h, synthesized and that exact line of code works in a method below this function. Only when I move the line of code up to this function does it fail.

 NSString* myfunc( int x )
 {
    NSString *myString = @"MYDATA";
    image1.image = [UIImage imageNamed:@"image1.png"];  // fails to compile
    return myString;        
 }

Shouldn't image1 be recognized anywhere within this particular .m file?

回答1:

myfunc is a C-style function here, not an Objective-C method in your class scope, so you can't see your instance variable image1.

you want to declare it as a method:

- (NSString *)myFuncWithParam:(int)x
{
  ...
}