Re: NSString* kMyKey = @"aKey" vs #define MYKEY @"aKey"
Re: NSString* kMyKey = @"aKey" vs #define MYKEY @"aKey"
- Subject: Re: NSString* kMyKey = @"aKey" vs #define MYKEY @"aKey"
- From: Dave Keck <email@hidden>
- Date: Fri, 3 Apr 2009 22:35:02 -1000
(Sorry for the thread-hijack, but I suppose I should finish what I've
started. Last message I promise :))
> Assuming I've got my const's straight, "NSString *const" makes the pointer
> const, but not the thing pointed to -- "const NSString *const" would make
> the pointer *and* the value const, but I doubt the compiler actually has the
> concept of const-ness of objects. (And NSString's immutability is a run-time
> thing.)
Hah, of course. This wouldn't be the first time I've confused myself
over 'const'.
At any rate, I've done a little more research, and it seems I was
wrong - constant NSStrings are not formed at runtime. A constant
NSString is completely contained in the binary (in the __DATA,
__cfstring segment) and has four fields - one that specifies the Obj-C
isa, a field for flags, a field that's a pointer to the actual
C-string (the C-string is contained in the __TEXT, __cstring segment),
and finally, a field containing the length of the C-string.
In the example I linked to in the last email, I was modifying the
bytes at the address of the NSString, but since it's contained in the
read/write __DATA segment, it's no surprise that the app didn't crash.
(And to prove my sanity, I tried writing to the NSString's referenced
C-string - which crashed. Phew.)
So, here's an example illustrating how to form an NSString at runtime
in the same fashion that the compiler forms constant NSStrings at
compile-time (which it then sticks in the binary):
http://www.docdave.com/halla2.zip
(If this isn't the epitome of 'defeating the purpose', I don't know what is...)
Also, this link has some great info on the subject:
http://jens.ayton.se/blag/objc-constant-objects/
Perhaps someone will find this information useful.
David
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden