I was just looking through my code and wondering about the standards of obj.c in xcode. We have all these NS(insert object type) which overlap with the original C, C++ objects. I wanted to clarify between different alternatives of snippets of code. Ev开发者_如何学编程en better than explaining each one would be a link to a guide or reference containing all these.
object.property = blah;
or [object setProperty:blah];
float aFloat = 0.01;
(or double
) or CGFloat aFloat = 0.01
int anInt = 1
or NSInteger anInt = 1
@"%d", anInt
or @"%i", anInt
Thanks
The first one (dot notation vs method calls) is purely a thing of taste. man printf
says that %d
and %i
both are placeholders for signed decimal, hence ObjC being strict superset of C doesn't change their meaning.
Types with NS
or CG
prefixes are platform dependent and are actually typedef
'ed from standard C types. If you decide to compile for different platforms (say 32/64 bit) using NS/CG types will fall back to default types of the platform you're compiling for. Take for example NSInteger
(snippet from NSObjCRuntime.h):
#if __LP64__ || (TARGET_OS_EMBEDDED && !TARGET_OS_IPHONE) || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif
It shows that if you're not compiling for iOS, the NSInteger will stand for long
, otherwise - it will be simple int
.
Personal opinion
I always use %d
since I saw it first in some ObjC tutoria. Never looked back on other placeholders for integers (unless %lld
). I use the dot notation only if receiver type is known at compile time. Sometimes you may have to write this:
id possiblyView = [someObject someView];
// the following line will give compile warning
possiblyView.frame
// the following line won't
[possiblyView frame];
The result of those calls is the same, but the first line forces compiler look for frame
variable under id-typed structure.
And I always try to use the NS/CG variable types since they make code look more ObjC-ish than C-ish.
精彩评论