问题
(or set multiple objects with one value) Is there a way to send multiple objects one message in one line.
So like
[someObject, otherObject reset];
like in LUA scripts (which I believe is C?) you can set mutliple objects:
someThing, otherThing = 1 , 0
回答1:
In short, no, neither Objective-C nor C support this feature. As an extreme measure, you can use -[NSArray makeObjectsPerformSelector:]
and -[NSArray makeObjectsPerformSelector:withObject:]
, such as
[[NSArray arrayWithObjects:someObject, otherObject, nil] makeObjectsPerformSelector:@selector(reset)];
回答2:
I would probably use an NSNotification.
You would need to subscribe those objects to your notification and send it. Both of these objects will receive the notification.
For instance, if your objects are ViewControllers, you could add this bit to their viewDidLoad method.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reset:) name:@"reset" object:nil];
The metod reset: has to be of this form:
- (void)reset:(NSNotification *)theNotification;
Then when you want to send your message to all of these objects you post the notification.
NSDictionary *messages = [NSDictionary dictionaryWithObjectsAndKeys:@"hello", @"object 1", @"bye", @"object2", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"reset" object:message];
So each object will receive the dictionary messages and will perform the method reset.
In order to use the method as a dictionary you'd have to get the object from the notification.
NSDictionary *receivedMessage = [theNotification object];
Also, don't forget to remove these objects from the notification center. I use this bit in their dealloc method:
[[NSNotificationCenter defaultCenter] removeObserver:self];
回答3:
Not really. That is one of the special features of Lua (NOT LUA) and Matlab.
You could consider using NSNotificationCenter and send a message to multiple objects that way, but it's more work.
回答4:
There are a couple methods in NSArray that can help with this:
- (void)makeObjectsPerformSelector:(SEL)aSelector
and
- (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)anObject
来源:https://stackoverflow.com/questions/3158629/send-message-to-multiple-objects-at-once-objective-c