Аргументы в @selector

Я видел некоторые сторонние платформы управления стиля HUD, которые включают стиль панели NSProgressIndicator, но к сожалению я не помню когда-либо видеть счетчик. Если Вы не можете найти способ заставить это делать то, что Вы хотите, , эта страница может генерировать анимированный gif, который мог бы быть полезным для того, чтобы сделать Ваше собственное.

35
задан Srikar Appalaraju 5 July 2011 в 06:21
поделиться

4 ответа

You could use the NSTimer method:

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds
                                 invocation:(NSInvocation *)invocation
                                    repeats:(BOOL)repeats;

Instead, since an NSInvocation object will allow you to pass arguments; an NSInvocation object is, as the docs define it:

an Objective-C message rendered static, that is, it is an action turned into an object.

Whilst creating an NSTimer object using a selector requires the format of the method being:

- (void)timerFireMethod:(NSTimer*)theTimer

An NSInvocation allows you to set the target, the selector, and the arguments that you pass in:

SEL selector = @selector(myMethod:setValue2:);

NSMethodSignature *signature = [MyObject instanceMethodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setSelector:selector];

NSString *str1 = @"someString";
NSString *str2 = @"someOtherString";

//The invocation object must retain its arguments
[str1 retain];
[str2 retain];

//Set the arguments
[invocation setTarget:targetInstance];
[invocation setArgument:&str1 atIndex:2];
[invocation setArgument:&str2 atIndex:3];

[NSTimer scheduledTimerWithTimeInterval:0.1 invocation:invocation repeats:YES];

Where MyObject is the class that myMethod:setValue2: is declared and implemented on – instanceMethodSignatureForSelector: is a convenience function declared on NSObject which returns an NSMethodSignature object for you, to be passed to NSInvocation.

Also, to note, with setArgument:atIndex:, the indices for arguments to be passed to the method set as the selector start at index 2. From the docs:

Indices 0 and 1 indicate the hidden arguments self and _cmd, respectively; you should set these values directly with the setTarget: and setSelector: methods. Use indices 2 and greater for the arguments normally passed in a message.

56
ответ дан 27 November 2019 в 06:46
поделиться

For scheduledTimerWithTimeInterval:, the selector you pass can only have one argument. Further, its one argument must be an NSTimer * object. In other words, the selector must take the following form:

- (void)timerFireMethod:(NSTimer*)theTimer

What you could do is store the arguments in the userInfo dictionary and call the selector you want from the timer callback:

- (void)startMyTimer {
    /* ... Some stuff ... */
    [NSTimer scheduledTimerWithTimeInterval:0.1 
                                     target:self 
                                   selector:@selector(callMyMethod:) 
                                   userInfo:[NSDictionary dictionaryWithObjectsAndKeys:someValue, 
                       @"value1", someOtherValue, @"value2", nil] 
                                    repeats:YES];
}

- (void)callMyMethod:(NSTimer *)theTimer {
    NSString *value1 = [[theTimer userInfo] objectForKey:@"value1"];
    NSString *value2 = [[theTimer userInfo] objectForKey:@"value2"];
    [self myMethod:value1 setValue2:value2];
}
27
ответ дан 27 November 2019 в 06:46
поделиться
@selector(myMethod:setValue2:)

Since the selector for your method isn't just called myMethod but instead myMethod:setValue2:.

Also (and I could be off base here), I believe technically you can drop the words between colons and thus also use @selector(myMethod::) but don't quote me on this unless others can confirm it.

-2
ответ дан 27 November 2019 в 06:46
поделиться

Без примера реализации вашего базового класса трудно дать конкретная информация. Но на ум приходят несколько вещей:

  1. Абстракция базы данных - это сложный материал для начала. Я понимаю, что вы хотите, чтобы он был стройным, чистым и подлым, но я думаю, что это чертовски сложно. Вам действительно нужно внимательно изучить спецификации различных движков БД, чтобы увидеть, какие части являются общими, а какие требуют специализации. Также; вы уверены, что абстракция БД не смешана с шаблоном шлюза табличных данных, поскольку вы говорите о добавлении таблиц БД путем расширения базового класса?

  2. Методы вашего текущего базового класса могут делать слишком много и / или не являются достаточно общими для начала, если расширенные классы изгибаются назад, чтобы держать его в чистоте. Может быть, вам следует разбить методы интерфейса базового класса на более мелкие защищенные методы, которые являются достаточно общими, чтобы их можно было повторно использовать в методах переопределения расширенных классов? Или наоборот: может быть, вам следует иметь перехватчики для переопределяемых методов в ваших интерфейсных методах.

  3. Согласно пункту 2: What '

2
ответ дан 27 November 2019 в 06:46
поделиться
Другие вопросы по тегам:

Похожие вопросы: