views:

54

answers:

3

(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
A: 

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.

John Smith
actually more langs support it than you think -- python for one
Jared P
+2  A: 

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)];
Jared P
+1  A: 

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];
OlivaresF