Tutorial :Objective C: Access of primitive data type


I want to access primitive data types like int, Bool in Objective C. I have created one class in which I declared an integer varriable. Now in other class i want to access this data and also set the value of it.

As in Objective C setter methods are applicable only for objects and I can't convert int to object.

So how would I be able to access the data ?

Please suggest some approach.


As in Objective C setter methods are applicable only for objects and I can't convert int to object.

Where did you get that idea. You can have Objective-C properties that are primitive types using either properties or normal accessors.

// in the .h file  // intIVar and otherIntIvar are int instance variables    @property (assign) int myIntIVar;  //         ^^^^^^ stops the runtime from sending retain or copy to synth'd ivars  -(int) myOtherIntIVar;  -(void) setMyOtherIntIVar;    // in the .m file    @synthesize myIntIVar = intIVar;    -(int) myOtherIntIVar  {      return otherIntIVar;  }    -(void) setMyOtherIntIvar: (int) newValue  {      otherIntIvar = newValue;  }  


You can use getters and setters with primitives.

Just use @synthesize, or create your own methods:

- (int)primitiveIvar;  - (void)setPrimitiveIvar:(int)_ivar;  


chpwn is correct and answers your question directly. This is just additional info.

If you want to convert a primitive value to an object, like for use in an NSArray, you wrap it in an NSNumber like this:

NSNumber *someValue = [NSNumber numberWithInt: 5];    

The same thing applies to float, BOOL, char, double and a ton of other primitive types.

To put the object value back into a primitive:

int someInteger = [someValue intValue];    

Rule of thumb:

If you're doing lots of math operations, need a number for local use, or need high performance, use primitives.

If you're storing values in the collection classes (NSArray, NSSet, NSDictionary etc…) and need object-like behaviors such as membership tests, predicate filtering, easy saving to disk or plist creation, use NSNumber.

Have a look at the NSNumber class documentation for more info.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »