當然可以。 (c):)
對於我建議工作的解決方案,您需要能夠通過方法訪問(設置/獲取)變量(很容易使用屬性或編寫自己的setters和getters)。
下面是一個例子:
- (void)performAction:(NSMutableString *)text {
[(UIImageView *)[self performSelector:NSSelectorFromString([text stringByAppendingString:@"Pic1"])] setHidden:YES];
[(UIImageView *)[self performSelector:NSSelectorFromString([text stringByAppendingString:@"Pic2"])] setHidden:NO];
}
至於我其實想過只是給你一個示例代碼使用Objective-C的這一大特點儘快,我會做得到啓動性能。雖然我不確定要深入討論這個主題,因爲它可能需要太多的互聯網文件,所以這就是爲什麼在示例代碼之後,我還會添加一些鏈接以供進一步閱讀。
@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
警告:我非常快速地跑完了足部。 Here's a nice tutorial at CocoaCast blog - Properties in Objective-C 2.0,我認爲這可能是一個很好的起點。順便說一句,他們提供了大量的學習資料(播客,屏幕錄像等),因此進一步瀏覽他們的網站可能會有用。當然,學習Objective-C和Cocoa的主要地方是官方文檔here's where it is about properties。
一個提醒:不要忘記請將有用的答案標記爲有用,並將其作爲您的問題所接受的最有用的答案 – 2010-01-20 13:41:02