key-value coding and to-many relationships - objective-c

I'm a bit confused with key value coding and to-many relationships. I've read that when having such relationship I should use [object mutableArrayValueForKey:#"key"]; to retrieve
the mutable array that holds the objects in that ordered relationship.
What I don't understand is what's the difference between mutableArrayValueForKey or just
valueForKey.
Let me illustrate with an example (array is an NSMutableArray of self setup as a property):
id array1= [self valueForKey:#"array"];
NSLog(#"first element %#",[array1 objectAtIndex:1]);
id array2 = [self mutableArrayValueForKey:#"array"];
NSLog(#"first element %#",[array2 objectAtIndex:1]);
Both calls return exactly the same. In that case, what is the benefit or different of the second one?
Cheers!

mutableArrayValueForKey does not return "array", it returns a proxy for "array." You can see this if you print out the classes:
NSLog(#"%#", [self.array class]);
NSLog(#"%#", [[self valueForKey:#"array"] class]);
NSLog(#"%#", [[self mutableArrayValueForKey:#"array"] class]);
This prints:
2010-02-24 20:06:44.258 Untitled[25523:a0f] NSCFArray
2010-02-24 20:06:44.275 Untitled[25523:a0f] NSCFArray
2010-02-24 20:06:44.276 Untitled[25523:a0f] NSKeyValueSlowMutableArray
Read over the documentation for mutableArrayValueForKey for details on how that proxy works. In this particular case, you happen to have a real NSMutableArray as an ivar. But what if there were no such ivar? You can implement KVC without an ivar backing the property, with methods like countOf<Key> and objectIn<Key>AtIndex:. There's no rule that there be an actual "array" ivar, as long as you can return sensible results to the KVC methods.
But what if you want to expose an NSMutableArray interface, but you don't have a real NSMutableArray? That's what mutableArrayValueForKey is for. It returns a proxy that when accessed will translate into KVC methods back to you, including sending you mutating to-many methods like insertObject:in<Key>AtIndex:.
This even happens in the case that you have a real ivar (as in your case), you just don't notice it because the proxy behaves so much like the real object.

The first element is actually objectAtIndex:0, not objectAtIndex:1.
Also, the second method ensures that you can modify the returned array with addObject: and removeObjectAtIndex:, even if the value for the key #"array" is an immutable array.

Related

How to check assignment since addObject doesn't access setter?

I just noticed that calling addObject: on an NSMutableArray doesn't access that array's setter.
E.g., for NSMutableArray self.myArray, [self.myArray addObject:object] does not use [self setMyArray:array] to add the object.
Previously I have been using custom setters and getter to check assignment before assigning; e.g., if I wanted an array that only accepted objects of class MyClass, I would do the following:
- (void)setMyArray:(NSMutableArray *)myArray
{
for (id object in myArray)
{
if (![object isKindOfClass:[MyClass class]]) return;
}
_myArray = myArray;
}
- (NSMutableArray *)myArray
{
if (!_myArray) _myArray = [[NSMutableArray alloc] init];
_myArray = myArray;
}
How do I go about achieving this same functionality when changing the array via addObject:, removeObject:, and other similar functions that may circumvent the setter?
Generally this kind of problem is the reason why NSMutableArray is usually avoided in preference of NSArray.
This is the simple solution, use NSArray instead of NSMutableArray:
self.myArray = [self.myArray arrayByAddingObject:foo];
However, if the array is really big that will cause performance issues. Then you've got two options:
you can have your own addObjectToMyArray: method in your class and always use that
you can create an NSArrayController and use that to access your array. It will implement key value observing and bindings and all of that stuff.
NSMutableArray is designed to perform addObject: with as few CPU instructions as possible and therefore does not proved any way for external code to be notified that the object was added. You have to have some other class wrapped around it.
Do not try to subclass NSMutableArray, because it is a "class cluster" making subclasses extremely complicated.
If what you wish to do is ensure objects in the array are of a particular class then this answer to the question "NSMutableArray - force the array to hold specific object type only" provides code to do exactly that.
If you wish to do other checks on assignment then you can use the code in that answer as a starting point.

Can the NSMultableArray mention which object inside the NSMultableArray?

The NSMutableArray can store every NSObject, but can I mention the NSMutableArray can get store my item only, for example, a NSMutableArray that store NSString only?
I remember that the java array can do that, can the objective C array do the similar things? Thanks.
Objective-C does not have this kind of generic constraint on NSArray/NSMutableArray. You have therefore two solutions:
Subclass NSArray/NSMutableArray and check for element type. It is strongly discouraged as NSArray/NSMutableArray is a class "cluster" and not obvious to subclass.
Create a category with specific methods that check the right type. You will have a compile-time enforcement of the type.
You can try it like this -
NSMutableArray *arr = [[[NSMutableArray alloc] init] autorelease];
if([obj isKindOfClass:[NSString class]])
[arr addObject:obj];
This way you end up adding only NSString to your arr.
Not by default, no. NSArray and its mutable counterpart just store pointers which happen to point obj-c objects. These objects can of any type. It would be up to you to make sure that only NSString's get in your array.
You could potentially subclass NSArray and override the addObject: methods such that they throw an exception if you try to add a non-NSString object.

What is an NSCFDictionary?

I'm getting an NSCFDictionary returned to me and I can't figure out how to use it. I know it's of type NSCFDictionary because I printed the class and it came out as __NCSFDictionary. I can't figure out how to do anything with it.
I'm just trying to hold onto it for now but can't even get that to work:
NSDictionary *dict = [[NSURLCredentialStorage sharedCredentialStorage] allCredentials];
for(NSURLProtectionSpace key in [dict keyEnumerator])
{
NSCFDictionary *value = [dict objectForKey:key];
}
The class reference for allCredentials says its supposed to return a dictionary whose values are also dictionaries. My assignment statement isn't working though. Do I need a cast of some kind?
NSDictionary and the other collection classes are actually class clusters: several concrete subclasses classes masquerading under the interface of a single class: they all provide the same functionality (because they are subclasses of the same class — in NSDictionary's case, this involves the three "primitive methods" -count, -objectForKey:, and -keyEnumerator), but have different internal workings to be efficient in different situations, based on how they're created and what type of data they may be storing.
NSCFDictionary is simply a concrete subclass of NSDictionary. That is, your NSDictionaries may actually be NSCFDictionary instances, but you should treat them as instances of NSDictionary, because that will provide you with the required dictionary-storage functionality.
NSDictionary *value = [dict objectForKey:key];
Now, another reason your code doesn't work: NSURLProtectionSpace is a class, so you should use it as a pointer, like this:
for (NSURLProtectionSpace *key ...
NSCFDictionary is the private subclass of NSDictionary that implements the actual functionality. It's just an NSDictionary. Just about any NSDictionary you use will be an NSCFDictionary under the hood. It doesn't matter to you code. You can type the variable as NSDictionary and use it accordingly.
I have an NSCFDictionary that is actually a NSMutableDictionary object, I can delete items from it. I mention this to further clarify jtbandes' answer: the NSCFDictionary object may be any object that inherits from NSDictionary.

What's safe to assume about the NSMutableArray / NSArray class cluster?

I know you shouldn't use this to decide whether or not to change an array:
if ([possiblyMutable isKindOfClass:[NSMutableArray class]])
But say I'm writing a method and need to return either an NSMutableArray or an NSArray, depending on the mutability of possiblyMutable. The class using my method already knows whether or not it's acceptable to change the returned array. Whether or not it's acceptable to change the returned array directly correlates with whether or not it's acceptable to change possiblyMutable.
In that specific case, is this code safe? It seems to me that if it's not acceptable to change the array, but we accidentally get a mutable array, it's ok, because the class using my method won't try to change it. And if it is acceptable to change the array, then we will always get possiblyMutable as an NSMutableArray (though this is the part I'm not entirely clear on).
So... safe or not? Alternatives?
No. Not safe at all.
If you do:
NSMutableArray * ma = [NSMutableArray arrayWithObject:#"foo"];
NSArray * aa = [NSArray arrayWithObject:#"foo"];
NSLog(#"Mutable: %#", [ma className]);
NSLog(#"Normal: %#", [aa className]);
Then you get:
2010-04-05 13:17:26.928 EmptyFoundation[55496:a0f] Mutable: NSCFArray
2010-04-05 13:17:26.956 EmptyFoundation[55496:a0f] Normal: NSCFArray
You also can't do:
NSLog(#"Mutable add: %d", [ma respondsToSelector:#selector(addObject:)]);
NSLog(#"Normal add: %d", [aa respondsToSelector:#selector(addObject:)]);
Because this logs:
2010-04-05 13:18:35.351 EmptyFoundation[55525:a0f] Mutable add: 1
2010-04-05 13:18:35.351 EmptyFoundation[55525:a0f] Normal add: 1
The only ways to guarantee you have a mutable array are to take the -mutableCopy of an existing array or if the return type of a function/method guarantees the array will be mutable.

How careful are you with your return types in Objective-C?

Say you have a method that returns a newly generated NSArray instance that is built internally with an NSMutableArray. Do you always do something like this:
- (NSArray *)someArray {
NSMutableArray *mutableArray = [[NSMutableArray new] autorelease];
// do stuff...
return [NSArray arrayWithArray:mutableArray]; // .. or [[mutableArray copy] autorelease]
}
Or do you just leave the mutable array object as-is and return it directly because NSMutableArray is a subclass of NSArray:
- (NSArray *)someArray {
NSMutableArray *mutableArray = [[NSMutableArray new] autorelease];
// do stuff...
return mutableArray;
}
Personally, I often turn a mutable array into an NSArray when I return from methods like this just because I feel like it's "safer" or more "correct" somehow. Although to be honest, I've never had a problem returning a mutable array that was cast to an NSArray, so it's probably a non-issue in reality - but is there a best practice for situations like this?
I used to do the return [NSArray arrayWithArray:someMutableArray], but I was slowly convinced that it doesn't offer any real benefit. If a caller of your API is treating a returned object as a subclass of the declared class, they're doing it wrong.
[NB: See bbum's caveat below.]
It's very common to return an NSMutableArray cast as an NSArray. I think most programmers would realize that if they downcast an immutable object and mutate it, then they're going to introduce nasty bugs.
Also, if you have an NSMutableArray ivar someMutableArray, and you return [NSArray arrayWithArray:someMutableArray] in a KVC accessor method, it can mess up KVO. You'll start getting "object was deallocated with observers still attached" errors.
NSArray is in fact a class cluster, not a type, anyway. So anywhere you see an NSArray, chances are it's already one of several different types anyway. Therefore the 'convert to NSArray' is somewhat misleading; an NSMutableArray already conforms to the NSArray interface and that's what most will deal with.
CocoaObjects fundamentals
In any case, given that you're returning an array (and not keeping it afterwards, thanks to the autorelease) you probably don't need to worry whether the array is mutable or not.
However, if you were keeping the array, then you might want to do this, to prevent the clients from changing the contents.