簡體   English   中英

如何使用公共方法訪問屬性。 “使用未聲明的標識符錯誤”

[英]How to access a property in a public method. “Use of undeclared identifier error”

這聽起來很基本,但我需要幫助。 我對Objective-C有點陌生。 因此,我有一個void方法來設置屬性。 我將如何在公共方法中使用相同的屬性? 這是代碼:

。H

 @property (strong, nonatomic) NSString *globalShowKey;

.M

  +(NSString *)fileStructure{

        NSString *mainDBPath = [PATH stringByAppendingPathComponent:CLIENT_KEY];

        NSString *subDirectory = [mainDBPath stringByAppendingPathComponent:globalShowKey];



        return subDirectory;
    }

有人可以給我解釋一下實現此目標的最佳方法是什么? 我非常接近實現這一目標! 如果我不清楚,請告訴我。

您正在使用self in class方法,因為方法定義中的+表示其類方法,而在class方法中self表示class而不是class實例。這行引起麻煩

   //self represent here class not instance but you need to access instance variable through property
    NSString *subDirectory = [mainDBPath stringByAppendingPathComponent:self.globalShowKey];

使用-代替+ in方法,因為+表示類方法,而-表示實例方法

 -(NSString *)fileStructure{

        NSString *mainDBPath = [PATH stringByAppendingPathComponent:CLIENT_KEY];

        NSString *subDirectory = [mainDBPath stringByAppendingPathComponent:self.globalShowKey];
        return subDirectory;
    }

現在在類實例上調用該方法,例如:如果此方法是在類Abc定義的,而不是使用[Abc fileStructure]; 使對象成為Abc

Abc *abc = [[Abc alloc] init];
NSString *fileStructure = [abc fileStructure];

編輯 :如果不更改NSString *const GlobalShowKey = @"abc";self.globalShowKey應用程序,也可以將self.globalShowKey設為常量字符串NSString *const GlobalShowKey = @"abc"; //在#import語句后寫

然后您可以使用先前的class method附加此全局密鑰

 +(NSString *)fileStructure{

        NSString *mainDBPath = [PATH stringByAppendingPathComponent:CLIENT_KEY];

        NSString *subDirectory = [mainDBPath stringByAppendingPathComponent:GlobalShowKey];
        return subDirectory;
    }

並稱呼它

[Abc fileStructure];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM