Objective C convention: When to use For and when to use With Objective C convention: When to use For and when to use With objective-c objective-c

Objective C convention: When to use For and when to use With


I actually think it is much simpler than what most answers think. I think it has less to do with complex programming language specifics, and has more to do with the uniqueness of the object in question.

When you say viewWithTag:, you are asking the UIView for any view that has that tag. There might be several. The UIView will return one of 'em.

However, objectForKey: (to me) sounds like there should be a single object (or nil) associated with that key. So, the key kinda exists and is bound (tightly coupled) to a single object.

EDIT:

There is an answer mentioning the existence of "by", which further implies how the convention has nothing to do with programming language complexities. It's just natural English.

NSString's stringByAppendingString:, for example, uses by, only because the function is written with a the verb appending. You can't say withAppending, that's bad English.


From my observation

While setting/getting the objects, you use WITH.

e.g. For setting of NSMutableArray object

 - (id)initWithCapacity:(NSUInteger)numItems

While setting/getting the properties for objects, you use FOR.

e.g.For setting value for property of type NSMutableDictionary

- (void)setValue:(id)value forKey:(NSString *)key

Hope this helps in clearing your doubt


It seems like with is used for properties that directly belongs to an object. A UIView has a tag property so viewWithTag:14 could be rephrased as "Find the view whose tag property is 14".

When you put an object in a dictionary, associated to a key, this key is not necessarily part of the object itself. objectForKey:@"foo" is a way to say "Look for an object that's linked to the key "foo".