在xcode中使用静态变量

时间:2012-10-06 13:21:36

标签: objective-c static

在我的项目中,我有一个搜索栏。

如果搜索栏中的文字发生变化,我需要知道

所以我声明两个静态NSMutableString来比较如下

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;
    }
}

它只是库存,我不知道为什么。

1 个答案:

答案 0 :(得分:0)

如果您希望在文本字段中的文本发生更改时收到通知,请在文本字段中添加目标/操作:

@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