Objective c 在xcode中使用静态变量
在我的项目中,我有一个搜索栏 如果搜索栏中的文本发生了变化,我需要知道 所以我声明两个静态NSMutableString进行比较,如下所示Objective c 在xcode中使用静态变量,objective-c,static,Objective C,Static,在我的项目中,我有一个搜索栏 如果搜索栏中的文本发生了变化,我需要知道 所以我声明两个静态NSMutableString进行比较,如下所示 static NSMutableString *latestKeyWord; static NSMutableString *secondaryKeyWord; - (void)viewDidLoad { [super viewDidLoad]; [testViewController setSecondaryKeyWord:SBar.tex
static NSMutableString *latestKeyWord;
static NSMutableString *secondaryKeyWord;
- (void)viewDidLoad
{
[super viewDidLoad];
[testViewController setSecondaryKeyWord:SBar.text];
[testViewController setLatestKeyWord:SBar.text];
[testViewController changeKeyWord];
}
+(void)setSecondaryKeyWord:(NSMutableString*) text
{
if (!secondaryKeyWord) {
secondaryKeyWord = [NSMutableString stringWithCapacity:200];
}
[secondaryKeyWord setString:text];
}
+(void)setLatestKeyWord:(NSMutableString*)text
{
if (!latestKeyWord) {
latestKeyWord = [NSMutableString stringWithCapacity:200];
}
[latestKeyWord setString:secondaryKeyWord];
}
-(BOOL)changeKeyWord
{
if ( ! [latestKeyWord isEqualToString:secondaryKeyWord]) {
NSLog(@"changed");
return TRUE;
}else {
NSLog(@"not change");
return FALSE;
}
}
它刚刚库存,我不知道为什么。如果您希望在文本字段中的文本发生更改时收到通知,请在文本字段中添加目标/操作:
@interface ViewController : UIViewController
@property (nonatomic) UITextField *field;
@property (nonatomic) NSString *searchText;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect frame = CGRectMake(50, 50, 200, 25);
self.field = [[UITextField alloc] initWithFrame:frame];
[self.field addTarget:self action:@selector(textChanged:)
forControlEvents:UIControlEventEditingChanged];
[self.view addSubview:self.field];
}
- (void)textChanged:(id)sender {
self.searchText = self.field.text;
NSLog(@"Text changed to: %@", self.searchText);
// restart searching here.
}
@end
你想干什么?为什么使用静态变量而不是实例变量?为什么
NSMutableString
不是一个简单的NSString
?我正在解析一个网站。我有另一个名为pageNumber的静态NSInteger和另一个名为startParsing的函数。当我第一次调用starParsing时,它会解析第1页,第二次解析第2页等等。。所以pageNumber就是记住下一步需要解析的页面。如果搜索栏中的文本更改了页码,则需要重置(pageNum=0
),我声明两个NSMutableString
进行比较。我使用NSMutableString
是因为静态变量只使用前缀为“+”的方法,并且我没有发现该方法可以在NSString中使用capasity进行初始化。谢谢你的回复!那么,当文本字段中的文本发生更改时,您希望收到通知吗?它起作用了!谢谢但是我对[self.field addTarget:self action:@selector(textChanged:)forControlEvents:UIControlEventEditingChanged]中的第一个参数有点困惑代码>。在我看来,它总是self