[cfe-dev] [] NSArray index and NSDictionary key syntax for other types?
Rick Mann
rmann at latencyzero.com
Sat Feb 15 14:41:47 PST 2014
On Feb 14, 2014, at 00:45 , Ted Kremenek <kremenek at apple.com> wrote:
> Hi Rick,
>
> I don’t think what you want could be done in a type safe way.
>
> What we have here is essentially an “informal protocol” that all Objective-C objects conform to, but the methods are “optional”. What this means is that you can actually use the subscript syntax on “id”:
>
> id x = …
> x[key] = …
>
> Since every Objective-C pointer type is convertible to ‘id’, they all need to implement this informal protocol in the same way.
>
> For example, suppose your special class ‘Foo’ had this attribute that said that other methods implement the subscripting. The following would then break:
>
> Foo *y = …
> y[key] = value; // works
> id x = y;
> x[key] = value; // doesn’t work
>
> The problem here is that for ‘y[key]’ the compiler knows the specific type of the receiver and could use your specially marked methods, but if you assigned the same object to ‘id’ then the compiler would know longer know the correct methods to use and would default to the original ones. This fundamentally breaks type safety for this language feature.
Well, that's true, but I don't think that's unusual. It could simply issue a warning or error on the use against id, just like the dot-property syntax does.
>
> Cheers,
> Ted
>
> On Feb 13, 2014, at 2:40 PM, Rick Mann <rmann at latencyzero.com> wrote:
>
>> I just discovered the awesome [] operator for NSArray and NSDictionary. A number of places where I use -valueForKey: couldn't translate, because they aren't NSDictionary objects. I did a little reading, and learned that I need to implement -objectForKeyedSubscript:.
>>
>> I was wondering if it would make sense to add a declarative attribute to indicate which methods should be used for indexed and keyed subscripts of some types. In other words, if I implement -valueForKey: on some class, I'd like to declare to the compiler that that should be used for [key] accesses (similarly, I might implement -setValue:forKey:). If the types are valid, it would use it.
>>
>> Maybe this really isn't necessary given that I should be able to just implement -objectForKeyedSubscript:, but it would possibly remove an extra message send.
>>
>> --
>> Rick
>>
>>
>>
>> _______________________________________________
>> cfe-dev mailing list
>> cfe-dev at cs.uiuc.edu
>> http://lists.cs.uiuc.edu/mailman/listinfo/cfe-dev
>
--
Rick
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 204 bytes
Desc: Message signed with OpenPGP using GPGMail
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20140215/4de9d78c/attachment.sig>
More information about the cfe-dev
mailing list