开发者

objective c iphone integers

Is it true to say that when using integers when programming for iphone that you do not synthesize them and that you do not release them.

If it is true could s开发者_如何学Goomebody explain why?

I get errors everytime that I try to. Also if I set an @property for an integer value I too get errors


In Objective-C, an int is a primitive type, whereas an NSNumber (or other similar things) are objects. Primitive types, since they don't support many of the things objects do (like getter and setter methods), can only be declared

@property(assign) int x;

Similarly, you don't release them, because doing so would imply you're sending a -release message to a primitive, which doesn't support messaging. You can @synthesize or @dynamic them, but only if you give them the appropriate (assign) property.

The short version: primitives like int don't have messages or methods. Don't try to give them some.


You can synthesize int-s. But you must declare them as assign-properties:

 @property(assign) int X;


Two comments:

  • NSNumber is much slower than, say, int. In general, if you can get away with using scalar values then do so.

  • When defining properties, use 'nonatomic' wherever possible. It allows for a significant performance improvement (with some risks, of course, if you have more than one thread acting upon it).


If you declare your integer as an 'NSInteger' or a C-style primitive int, then what you say is true. But not if you are using the NSNumber class. Let me explain:

NSInteger is not an Objective-C class.It is nothing more than a synonym for an integer. NSInteger is defined like this:

#if __LP64__ || NS_BUILD_32_LIKE_64
  typedef long NSInteger;
  typedef unsigned long NSUInteger;
#else
  typedef int NSInteger;
  typedef unsigned int NSUInteger;
#endif

NSNumber is an Objective-C class, and a subclass of NSValue. It is possible to create a NSNumber object from a signed or unsigned char, short int, int, long int, long long int, float, double or BOOL. Among the two, NSNumber can only be used in collections, such as NSArray, where an object is required, but NSInteger cannot be used there directly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜