在objective-c中使用参数作为变量名

Ant*_*ony 4 string function objective-c

我是Objective-c的新手并且遇到了问题.是否可以将函数的参数用作某些变量名?

例如,假设我有一堆图像:aPic1,aPic2,bPic1,bPic2,cPic1,cPic2,我想创建一个动作,这样每次单击一个按钮时,视图控制器将隐藏Pic1并显示Pic2,取决于单击哪个按钮.

- (void) performAction:(NSMutableString *) text
{
    [text appendString:@"Pic1"].hidden = YES;    //I wanna hide textPic1, which is a UIImageView
    [text appendString:@"Pic2"].hidden = NO;     //I wanna show textPic2, which is also a UIImageView
}
Run Code Online (Sandbox Code Playgroud)

我知道在这种情况下我不应该使用NSString或NSMutableString.任何人都知道如何通过这种功能实现我的目标?谢谢.

Iva*_*pan 5

是的你可以.(C) :)

对于我建议工作的解决方案,您需要能够通过方法访问(设置/获取)变量(使用属性轻松完成或编写自己的setter和getter).

这是一个例子:

- (void)performAction:(NSMutableString *)text {
    [(UIImageView *)[self performSelector:NSSelectorFromString([text stringByAppendingString:@"Pic1"])] setHidden:YES];
    [(UIImageView *)[self performSelector:NSSelectorFromString([text stringByAppendingString:@"Pic2"])] setHidden:NO];
}
Run Code Online (Sandbox Code Playgroud)

至于属性,我实际上只想给你一个示例代码,以便开始使用Objective-C ASAP的这个伟大功能,我将这样做.虽然我不确定深入研究这个主题,因为它可能需要太多的互联网论文,所以这就是为什么在示例代码之后我还会添加一些链接以供进一步阅读.

@interface AClass : NSObject {
    // Here's where you declare variables
    NSObject *objectForInternalUseWeWantToBeRetained;
    id linkToObjectUsuallyNotRetained;
    int nonObjectVariable;
    BOOL aVariableWithARenamedGetter;
}

// And here's where their properties are declared
@property (nonatomic, retain) NSObject *objectForInternalUseWeWantToBeRetained;
@property (nonatomic) id linkToObjectUsuallyNotRetained;
@property (nonatomic, assign) int nonObjectVariable;
@property (nonatomic, assign, getter=renamedVariableGetter) BOOL aVariableWithARenamedGetter;


@end


@implementation AClass

// Here we command the machine to generate getters/setters for these properties automagically
@synthesize objectForInternalUseWeWantToBeRetained, linkToObjectUsuallyNotRetained, nonObjectVariable, aVariableWithARenamedGetter;

// But you can implement any of the getters/setters by yourself to add some additional behaviour
- (NSObject *)objectForInternalUseWeWantToBeRetained {
    // Some additional non-usual stuff here

    // And after that we do the getters job - return the variables value
    return objectForInternalUseWeWantToBeRetained;
}

// And of course we don't forget to release all the objects we retained on dealloc
- (void)dealloc {
    [objectForInternalUseWeWantToBeRetained release];

    [super dealloc];
}


@end

// And here's where their properties are declared
@property (nonatomic, retain) UIImageView *testPic1;
@property (nonatomic, retain) UIImageView *testPic2;


@end
Run Code Online (Sandbox Code Playgroud)

警告:我很快就完成了这个问题.这是CocoaCast博客上的一个很好的教程 - Objective-C 2.0中的属性,我认为这可能是一个很好的起点.顺便说一句,他们提供了大量的学习资料(播客,截屏视频等),因此进一步浏览他们的网站可能会有用.当然,了解Objective-C和Cocoa的主要内容是官方文档,这里是关于属性的地方.