的@implementation
塊內聲明的專用塊是種危險的,在我看來,與其他OOP概念例如比較Java的。它看起來像成員變量,但有點靜態。
新手程序員可以很容易地欺騙它。我寫了一個測試程序,並對行爲感到驚訝。
@interface SomeClass : NSObject
{
NSString *forExample;
}
- (void) set:(NSString *)one another:(NSString *)another;
- (void)print;
@end
實現:
#import "SomeClass.h"
@implementation SomeClass
NSString *anotherExample;
- (void) set:(NSString *)one another:(NSString *)another
{
forExample = one;
anotherExample = another;
}
- (void)print{
NSLog(@"One = %@, another = %@", forExample, anotherExample);
}
@end
測試:
- (void)testClass {
SomeClass * s1 = [SomeClass new];
[s1 set:@"one one" another:@"one another"];
SomeClass *s2 = [SomeClass new];
[s2 set:@"two one" another:@"two another"];
[s1 print];
[s2 print];
}
和輸出是,
One = one one, another = two another
One = two one, another = two another
這是我懷疑你的答案非常有意義,但如果我嘗試訪問任何其他類中的anotherExample'(通過正確地在這些類中包含'Someclass'),編譯器告訴我這個變量是未聲明的。是什麼賦予了? – bitcruncher 2010-04-03 15:04:08
@bitcruncher,因爲'anotherExample'僅對聲明它的.m文件是全局的。如果你希望它可用於其他文件,那麼你必須在.h文件中聲明'extern NSString * anotherExample;',然後在你需要全局的地方''導入'.h文件。儘管它具有有效的用例,但是這種代碼異味仍然存在。 – 2010-04-03 15:26:28
沒有實際的代碼聞:-)這只是一個探索性問題。 – bitcruncher 2010-04-03 16:05:43