Reputation: 3334
Option 1:
typedef NSString MyString
Option 2:
typedef NSString * MyString
In Objective-C, both statement are valid, but from what I've seen people overwhelmingly choose option 2 over option 1. Is there a technical reason to that, or is it more of a convention?
Option 2 hides the fact that MyString
is a pointer. This might be the intention, but in objective-c it's more often than not that you do want to know whether you're dealing with a primitive type or a reference type.
In C, at least the convention is to give it a name like MyStringRef
to emphasize that it's a pointer, but I don't think I ever seen anyone does that in objective-c.
And then there's Swift.
Both option 1 and option 2 works perfectly fine when bridged to swift, but if I try to mark option1 as a enum-
typedef NSString MyString NS_STRING_ENUM;
FOUNDATION_EXPORT MyString * const MyStringOne;
the compiler starts to freak out. Syntax highlight and auto-completion breaks all the time. And something like var x = MyString.one
chokes the compiler straight out, leaving only the Segmentation fault: 11 error.
Upvotes: 3
Views: 910
Reputation: 53000
You are correct that this pattern is used when declaring “string enums” in Objective-C.
You ask why including the *
in the typedef
is preferred.
Well usually the reason is just one of subjective preference, either approach is valid. Note that Core Foundation uses type names such as CFStringRef
where the *
is hidden but the name contains Ref
to indicate this, however Objective-C does not follow and use NSStringRef
.
However you have found an objective reason to follow the usual pattern - the Swift compiler (at least in Xcode 8.2.1 I used and which one you used) is a sensitive creature and blows itself up with a memory fault if you use the other pattern.
First submit a bug to Apple (test first in Xcode 9 if you have it).
Then stick with the “preferred” pattern, unless you enjoy watching Swift commit compilercide ;-)
Upvotes: 2