Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers, primitives, and properties in Objective-C classes

I really need some clarification — I have a few questions and I'm all mixed up right now.

Here is a simple class interface:

#import <UIKit/UIKit.h>

@interface Car : NSObject{
    NSInteger carID;
    NSString *carName;
}

@property (nonatomic, assign) NSInteger carID;
@property (nonatomic, copy) NSString * carName;
@end
  1. Why is carID not declared as a pointer?
  2. Why does it use "assign" for carID instead of "copy"?
  3. Why even declare class members as pointers in the first place? (In my main program, my Car object will be used as a pointer.)
like image 209
qstar Avatar asked Aug 01 '26 20:08

qstar


2 Answers

NSInteger is simply a typedef for a primitive type (int on 32-bit, long on 64-bit) — it is not an object, and can as such not be retained or copied.

Class members are always pointers; you never pass the "real" objects around; as that would be, at best, unmanageable.

Edit: To expand on the last paragraph: Objective-C class instances always exist on the heap, never on the stack; this is to facilitate things like reference counting and self-managed object life cycle.

This also means that it's very hard to accidentally copy an object; but on the flip side it can be somewhat easier to accidentally dispose of an object you still need. Still, the latter is more readily debugged (as it causes a nice, big crash (at best, anyway)) than the last (which at worst causes a slow leak).

like image 151
Williham Totland Avatar answered Aug 03 '26 20:08

Williham Totland


The property for carID is not really correct. For types that are not pointers, the correct definition looks like:

@property (nonatomic) NSInteger carID;

It's always going to be copying a value anyway, but "copy" has a very different meaning in properties - for objects it's going to call [object copy] when that property is used to set a new value.

Or you could drop off the nonatomic, but then the property is more expensive to call (by some small amount). Just leave in the nonatomic unless you have a good reason not to.

like image 44
Kendall Helmstetter Gelner Avatar answered Aug 03 '26 19:08

Kendall Helmstetter Gelner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!